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) {
if(!head) return head;
map<RandomListNode *,RandomListNode *> dic;
RandomListNode *h= new RandomListNode(head->label),*p=head->next,*q=h;
dic[head] = h;
while(p)
{
RandomListNode * cur = new RandomListNode(p->label);
q->next = cur;
dic[p] = cur;
p = p->next;
q = q->next;
}
p = head;
q = h;
while(p)
{
if(p->random)
{
q->random = dic[p->random];
}
p = p->next;
q = q->next;
}
return h;
}
};