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.
Solution:
/**
* 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) {
RandomListNode *res = new RandomListNode(-1);
unordered_map<RandomListNode*, int> umRI;
unordered_map<int, RandomListNode*> umIR;
RandomListNode *p = head, *q = res;
int num = 0;
while(p)
{
RandomListNode* node = new RandomListNode(p->label);
q->next = node;
q = q->next;
umIR[++num] = q;
umRI[p] = num;
p = p->next;
}
q->next = NULL;
p = head;
q = res->next;
while(p)
{
if(!p->random) q->random = NULL;
else
{
num = umRI[p->random];
q->random = umIR[num];
}
p = p->next;
q = q->next;
}
return res->next;
}
};