Copy List with Random Pointer
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 *p=head;
RandomListNode *q;
while(p){
q=new RandomListNode(p->label);
q->next=p->next;
p->next=q;
p=q->next;
}
//处理random指针
p=head;
q=head->next;
while(p){
if(p->random)q->random=p->random->next;
else q->random=NULL;
p=q->next;
if(p)q=p->next;
}
//构造新链
RandomListNode *newhead=head->next;
p=head;
q=newhead;
while(p){
p->next=q->next;
p=p->next;
if(p){
q->next=p->next;
q=q->next;
}
}
return newhead;
}
};