-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode138.java
More file actions
51 lines (45 loc) · 1.32 KB
/
LeetCode138.java
File metadata and controls
51 lines (45 loc) · 1.32 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
import java.util.HashMap;
public class LeetCode138 {
public static void main(String[] args) {
// NOTE: 测试案例待补充
System.out.println("Hello LeetCode138");
}
}
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
class Solution138 {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
HashMap<Node, Node> map = new HashMap<>();
Node newHead = new Node(head.val);
map.put(head, newHead);
Node oldNode = head;
Node newNode = newHead;
while (oldNode.next != null) {
if (!map.containsKey(oldNode.next)) {
map.put(oldNode.next, new Node(oldNode.next.val));
}
if (oldNode.random != null && !map.containsKey(oldNode.random)) {
map.put(oldNode.random, new Node(oldNode.random.val));
}
newNode.next = map.get(oldNode.next);
newNode.random = map.get(oldNode.random);
oldNode = oldNode.next;
newNode = newNode.next;
}
if (oldNode.random != null) {
newNode.random = map.getOrDefault(oldNode.random, null);
}
return newHead;
}
}