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.
很经典的一道题。先将新旧链表按Z字形连起来,再更新新链表的random指针,最后拆分新旧链表。
/**
* 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 *new_head = new RandomListNode(head->label);
new_head->random = head->random;
//combine list
RandomListNode *p = head,*q = p->next,*r = new_head;
p->next = new_head;
while(q){
r->next = q;
p = q->next;
q->next = new RandomListNode(q->label);
r = q->next;
r->random = q->random;
q = p;
}
r->next = NULL;
p = new_head;
while(p->next){ if(p->random) p->random = p->random->next; p = p->next->next; }
if(p->random) p->random = p->random->next; //the last node
p = head;
//split list
while(p->next->next){
q = p->next;
p->next = q->next;
q->next = p->next->next;
p = p->next;
q = q->next;
}
p->next = NULL;
return new_head;
}
};