-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_138.java
More file actions
53 lines (40 loc) · 1.05 KB
/
Copy pathP_138.java
File metadata and controls
53 lines (40 loc) · 1.05 KB
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
package leetcode.medium;
public class P_138 {
private static class Node {
int val;
Node next;
Node random;
Node(int val) {
this.val = val;
}
}
public Node copyRandomList(Node head) {
Node iter = head, next;
while (iter != null) {
next = iter.next;
final Node copy = new Node(iter.val);
iter.next = copy;
copy.next = next;
iter = next;
}
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
iter = head;
final Node pseudoHead = new Node(0);
Node copy, copyIter = pseudoHead;
while (iter != null) {
next = iter.next.next;
copy = iter.next;
copyIter.next = copy;
copyIter = copy;
iter.next = next;
iter = next;
}
return pseudoHead.next;
}
}