-
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathCopyListWithRandomPointer.java
More file actions
77 lines (56 loc) · 1.45 KB
/
CopyListWithRandomPointer.java
File metadata and controls
77 lines (56 loc) · 1.45 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* Created by nikoo28 on 7/16/19 2:15 AM
*/
class Node {
public int val;
public Node next;
public Node random;
public Node() {
}
public Node(int _val, Node _next, Node _random) {
val = _val;
next = _next;
random = _random;
}
}
class CopyListWithRandomPointer {
private Map<Node, Node> oldNodeNewNodeMap = new HashMap<>();
private Node copyRandomList(Node head) {
if (head == null)
return null;
Node headCopy = head;
while (head != null) {
Node temp = new Node();
oldNodeNewNodeMap.put(head, temp);
temp.val = head.val;
head = head.next;
}
head = headCopy;
Node deepCopy = oldNodeNewNodeMap.get(head);
Node deepCopyHead = deepCopy;
while (head != null) {
Node next = head.next;
Node random = head.random;
deepCopy.next = oldNodeNewNodeMap.get(next);
deepCopy.random = oldNodeNewNodeMap.get(random);
head = head.next;
deepCopy = deepCopy.next;
}
return deepCopyHead;
}
public static void main(String[] args) {
CopyListWithRandomPointer copyListWithRandomPointer = new CopyListWithRandomPointer();
Node id1 = new Node();
Node id2 = new Node();
id1.val = 1;
id2.val = 2;
id1.next = id2;
id1.random = id2;
id2.next = null;
id2.random = id2;
System.out.println(copyListWithRandomPointer.copyRandomList(id1));
}
}