-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCopyListWithRandomPointer.java
More file actions
37 lines (33 loc) · 984 Bytes
/
CopyListWithRandomPointer.java
File metadata and controls
37 lines (33 loc) · 984 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
package com.dbc;
import java.util.HashMap;
import java.util.Map;
public class CopyListWithRandomPointer {
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) {
Node preHead = new Node(0);
Node curNode = preHead, pointNode = head;
Map<Node, Node> map = new HashMap<>();
while (pointNode != null) {
Node node = new Node(pointNode.val);
curNode.next = node;
curNode = curNode.next;
map.put(pointNode, curNode);
pointNode = pointNode.next;
}
for (Map.Entry<Node, Node> item : map.entrySet()) {
if (item.getKey().random != null) {
item.getValue().random = map.get(item.getKey().random);
}
}
return preHead.next;
}
}