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==NULL){
return head;
}
RandomListNode *newHead=NULL,*p=head,*q;
while(p!=NULL){
q= new RandomListNode(p->label);
q->next=p->next;
p->next=q;
p=q->next;
}
p=head;
while(p!=NULL){
q=p->next;
if(p->random!=NULL){
q->random = p->random->next;
}
p=q->next;
}
p=head;
newHead=head->next;
q=newHead;
while(p!=NULL){
p->next=q->next;
p=p->next;
if(p!=NULL){
q->next=p->next;
}else{
q->next=NULL;
}
q=q->next;
}
return newHead;
}
};