138. Copy List with Random Pointer
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(!head) return nullptr;
RandomListNode* cur = head, *next;
// copying each node right after the current node
while(cur){
next = cur->next;
RandomListNode* copyNode = new RandomListNode(cur->label);
cur->next = copyNode;
copyNode -> next = next;
cur = next;
}
// copying random pointer
cur = head;
while(cur){
next = cur -> next -> next;
if(cur->random)
cur->next->random = cur->random->next; // cur->random->next is the copy of corresponding random node
// for the current node in original linked list
cur = next;
}
// extract copy list and restore original list
cur = head;
RandomListNode *copyHead = head->next, *copyIter = copyHead;
while(cur){
next = cur -> next -> next;
if(next) copyIter->next = next -> next;
copyIter = copyIter->next;
cur->next = next;
cur = next;
}
return copyHead;
}
};Last updated
Was this helpful?