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.
解题思路:1.遍历链表,在旧节点后面插入同样的新节点,copy旧节点的label和random
2.遍历链表,将新节点的random值指向旧random节点的下一节点(即为新random节点)
3.将新旧链表分开,恢复旧链表结构,输出新链表
/**
* 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) {
RandomListNode copyHead=null;
RandomListNode point=head;
if(head==null){
return null;
}
while(point!=null){
RandomListNode copyNode=new RandomListNode(point.label);
copyNode.next=point.next;
copyNode.random=point.random;
point.next=copyNode;
point=point.next.next;
}
point=head;
while(point!=null){
if(point.next.random!=null){
point.next.random=point.random.next;
}
point=point.next.next;
}
point=head;
RandomListNode tmp=new RandomListNode(0);
copyHead=tmp;
while(point!=null){
tmp.next=point.next;
point.next=point.next.next;
point=point.next;
tmp=tmp.next;
}
tmp=copyHead;
copyHead=copyHead.next;
tmp.next=null;
return copyHead;
}
}