/**
* 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 == NULL)
return NULL;
RandomListNode
*cur = head,
*dummy = new RandomListNode(0),
*newHead = dummy,
*newCur = dummy;
std::unordered_map<RandomListNode*, RandomListNode*> mymap;
while(cur)
{
RandomListNode
*temp = new RandomListNode(cur->label);
temp->random = cur->random;
newCur->next = temp;
newCur = newCur->next;
mymap[cur] = temp;
cur = cur->next;
}
newCur = dummy->next;
while(newCur)
{
newCur->random = mymap[newCur->random];
newCur = newCur->next;
}
newHead = dummy->next;
delete dummy;
return newHead;
}
};
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.
Idea: if it is a single linked list, then just copy the value and the next pointer. However, if it added an additional random pointer, then, what should we do?
How to copy the random pointer? use the std::unordered_map<>