-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyRandomList.java
More file actions
41 lines (34 loc) · 976 Bytes
/
CopyRandomList.java
File metadata and controls
41 lines (34 loc) · 976 Bytes
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
import java.util.HashMap;
public class CopyRandomList {
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
HashMap<Node, Node> map = new HashMap<>();
Node cur = head;
// 1. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
while (cur!=null){
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
// 2. 构建新链表的 next 和 random 指向
while (cur!=null){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
// 3. 返回新链表的头节点
return map.get(head);
}
}