-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path138. Copy List with Random Pointer.java
66 lines (66 loc) · 1.92 KB
/
138. Copy List with Random Pointer.java
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
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
// create a duplicate LL
Node current = head;
while (current != null) {
Node nextnode = current.next;
Node newnode = new Node(current.val);
current.next = newnode;
newnode.next = nextnode;
current = nextnode;
}
current = head;
// set the random pointers
while (current != null) {
current.next.random = current.random != null ? current.random.next : null;
current = current.next.next;
}
// connect wisely
current = head;
Node dummy = new Node(-1);
Node temp = dummy;
while (current!=null) {
temp.next = current.next;
temp = current.next;
current.next = current.next.next;
current = current.next;
}
return dummy.next;
}
public Node copyRandomListBruteForce(Node head) {
Map<Node, Node> nodeMap = new HashMap<>();
Node current = head;
while (current!=null) {
nodeMap.put(current, new Node(current.val));
current = current.next;
}
current = head;
while (current!=null) {
Node node = nodeMap.get(current);
node.next = nodeMap.get(current.next);
node.random = nodeMap.get(current.random);
current = current.next;
}
return nodeMap.get(head);
}
}