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.
[code]
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head==null)return null;
RandomListNode p=head;
while(p!=null)
{
RandomListNode next=p.next;
p.next=new RandomListNode(p.label);
p.next.next=next;
p=next;
}
p=head;
RandomListNode newHead=p.next, q=newHead;
while(true)
{
q.random= p.random==null ? null : p.random.next;
p=q.next;
if(p==null)break;
q=p.next;
}
p=head;
q=newHead;
while(true)
{
RandomListNode next=q.next;
q.next=next==null ? null :next.next;
p.next=next;
p=next;
if(p==null)break;
q=p.next;
}
return newHead;
}
}
[Thoughts]
copy random 和 复原 原list不能同时进行, 因为p.random是前面的node, p.random.next 就错了