random的指针不知道指向这个list中的哪一个 或者null 所以假如简单的复制一个平行的list是不可以的 比如random指向一个还未被复制的node 或者指向一个无法再track回去的node
算法分三步1.把list每个node复制之后放在原node之后 连成一个list 2.从头至尾把copy的random指针弄好 3. 把list拆开
/**
* 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 iter = head, next;
while ( iter != null ){
next = iter.next;
RandomListNode copy = new RandomListNode ( iter.label );
iter.next = copy;
copy.next = next;
iter = next;
}
iter = head;
while ( iter != null ){
next = iter.next.next;
if ( iter.random != null ){
iter.next.random = iter.random.next;
}
iter = next;
}
iter = head;
RandomListNode dummy = new RandomListNode (0);
RandomListNode copyIter = dummy;
while ( iter != null ){
next = iter.next.next;
copyIter.next = iter.next;
iter.next = next;
copyIter = copyIter.next;
iter = next;
}
return dummy.next;
}
}