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.
首先在每一个节点后插入其自身的拷贝节点。拷贝节点的next和random指向原节点所指向的位置。 第二次循环时,我们将拷贝链表的random引用后移一位,使其指向拷贝节点。最后一次循环时,将链表拆分成为两个单独的链表。整体来看三个循环,第一个循环产生拷贝节点。第二个循环修正random引用位置,第三次修正next引用位置。
public class Solution {
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode curr = head;
while(curr != null) {
RandomListNode tmp = new RandomListNode(curr.label);
tmp.next = curr.next;
curr.next = tmp;
tmp.random = curr.random;
curr = curr.next.next;
}
curr = head;
while(curr != null) {
curr.next.random = curr.random == null ? null : curr.random.next;
curr = curr.next.next;
}
curr = head;
RandomListNode res = null;
while(curr != null && curr.next != null) {
if(res == null) {
res = curr.next;
}
RandomListNode tmp = curr.next;
curr.next = curr.next.next;
curr = tmp;
}
return res;
}
}