Problem
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.
Challenge
Could you solve it with O(1) space?
Note
因为O(1) space,所以no hashtable。新建两个结点n1 n2
,令n1 = head
,向后循环,同时不断复制n2
到n1.next
;再放回头结点,循环第二次,复制n2.random
到n1.random.next
,再放回头结点;再建立第三个结点n3 = n2
,循环第三次,令n1 n2
分离,返回头结点n3
,结束。
大体意思就是,先复制n1到n2,顺便将所有的n2放在n1.next;再复制所有的n1.random到n2.random,顺便将所有的n2.random放在n1.random.next;最后令n3 = n2,令n1 = n1.next.next, n2 = n2.next.next, 将n1和n2分离,返回n2的头结点n3.
Solution
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
RandomListNode n1 = head, n2, n3;
while (n1 != null) {
n2 = new RandomListNode(n1.label);
n2.next = n1.next;
n1.next = n2;
n1 = n1.next.next;
}
n1 = head;
n2 = n1.next;
while (n1 != null) {
n2.random = n1.random == null ? null : n1.random.next;
n1 = n1.next.next;
n2 = n1 == null ? null : n2.next.next;
}
n1 = head;
n2 = n1.next;
n3 = n2;
while (n1 != null) {
n1.next = n1.next.next;
n2.next = n2.next == null ? null : n2.next.next;
n1 = n1.next;
n2 = n2.next;
}
return n3;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。