Created
July 29, 2014 07:01
-
-
Save xiren-wang/2d427ffb8a76938be020 to your computer and use it in GitHub Desktop.
deep copy random list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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