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.
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) return NULL;
RandomListNode * src = head;
while(src)
{
RandomListNode * new_node = new RandomListNode(src->label);
new_node->next = src->next;
src->next = new_node;
src = src->next->next;
}
src = head;
while(src!=NULL)
{
if(src->random!=NULL)
src->next->random = src->random->next;
src = src->next->next;
}
src = head;
RandomListNode *dst = src->next;
RandomListNode * Dst = dst;
while(dst->next!=NULL)
{
src->next = src->next->next;
src = src->next;
dst->next = dst->next->next;
dst = dst->next;
}
src->next = src->next->next;
return Dst;
}
};