A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the 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) {
unordered_map<RandomListNode *,RandomListNode *> old2newmap;
RandomListNode *newhead = new RandomListNode(-1);
RandomListNode *temp = head;
RandomListNode *cur = newhead;
while(temp) {
RandomListNode *newNode = new RandomListNode(temp->label);
old2newmap[temp] = newNode;
cur->next = newNode;
cur = cur->next;
temp = temp->next;
}
temp = head;
while(temp) {
if(temp->random) {
old2newmap[temp]->random = old2newmap[temp->random];
}
temp = temp->next;
}
return newhead->next;
}
};