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.
思路:先在每一个节点的后面插入节点的副本,暂时不考虑random指向,比如说:p1->p2->p3->p4->.....->pn 将其变成p1->CoppyOf(p1)->p2->CoppyOf(p2)->p3->CoppyOf(p3)->p4->CoppyOf(p4)->.....->pn->CoppyOf(pn),再将每个CoppyOf(pi)的random指向pi的random的指向的下一个节点即可,最后该链表分奇数和偶数节点断开即可
/**
* 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 (RandomListNode)null;
RandomListNode p=head;
while(p!=null){
RandomListNode node=new RandomListNode(p.label);
node.next=p.next;
p.next=node;
p=p.next.next;
}
p=head;
RandomListNode q=head.next;
while(p!=null){
if(p.random!=null) q.random=p.random.next;
p=p.next.next;
if(p!=null) q=p.next;
else break;
}
p=head;
q=head.next;
RandomListNode myhead=head.next;
while(p!=null){
p.next=p.next.next;
p=p.next;
if(p!=null){
q.next=q.next.next;
q=q.next;
}else break;
}
return myhead;
}
}