-
Notifications
You must be signed in to change notification settings - Fork 657
/
Copy pathcloneLinkedListJava
62 lines (50 loc) · 1.4 KB
/
cloneLinkedListJava
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
Node iter = head;
Node front = head;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while (iter != null) {
front = iter.next;
Node copy = new Node(iter.val);
iter.next = copy;
copy.next = front;
iter = front;
}
// Second round: assign random pointers for the copy nodes.
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
// Third round: restore the original list, and extract the copy list.
iter = head;
Node pseudoHead = new Node(0);
Node copy = pseudoHead;
while (iter != null) {
front = iter.next.next;
// extract the copy
copy.next = iter.next;
copy = copy.next;
// restore the original list
iter.next = front;
iter = front;
}
return pseudoHead.next;
}
}