Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created July 29, 2014 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/2d427ffb8a76938be020 to your computer and use it in GitHub Desktop.
Save xiren-wang/2d427ffb8a76938be020 to your computer and use it in GitHub Desktop.
deep copy random list
/**
* 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) {
//copy each node to new list, and keep old value of random* pointer (to be updated later)
unordered_map<RandomListNode *, RandomListNode*> oldMapToNew;
RandomListNode * front = head;
RandomListNode *newHead = NULL;
RandomListNode *newTail = NULL;
while (front) {
RandomListNode *newNode = new RandomListNode(front->label);
newNode->random = front->random; //old, to be updated to new
oldMapToNew[front] = newNode;
if (!newHead) {
newHead = newNode;
newTail = newHead;
}
else {
newTail->next = newNode;
newTail = newNode;
}
front = front->next;
}
//update random pointer
front = newHead;
while (front) {
unordered_map<RandomListNode *, RandomListNode*>::iterator it = oldMapToNew.find(front->random);
if (it != oldMapToNew.end())
front->random = it->second;
front = front->next;
}
return newHead;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment