Poison

138. Copy List with Random Pointer

HashMap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}

Map<Node, Node> oldToNewMap = new IdentityHashMap<>();
Node node = head;
while (node != null) {
oldToNewMap.put(node, new Node(node.val));
node = node.next;
}

for (Map.Entry<Node, Node> entry : oldToNewMap.entrySet()) {
Node old = entry.getKey(), duplicate = entry.getValue();
duplicate.next = oldToNewMap.get(old.next);
duplicate.random = oldToNewMap.get(old.random);
}

return oldToNewMap.get(head);
}
}
Linked List
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
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}

Node curr = head;
while (curr != null) {
Node duplicate = new Node(curr.val);
Node next = curr.next;
curr.next = duplicate;
duplicate.next = next;
curr = next;
}

// nodeA -> duplicate nodeA -> nodeB -> duplicate nodeB -> ...

curr = head;
while (curr != null) {
Node duplicate = curr.next;
if (curr.random != null) {
duplicate.random = curr.random.next;
}
curr = duplicate.next;
}

Node duplicateHead = head.next;
curr = head;
while (curr != null) {
Node duplicate = curr.next;
Node next = duplicate.next;
curr.next = next;
if (next != null) {
duplicate.next = next.next;
}
curr = next;
}

return duplicateHead;
}
}
Reference

138. Copy List with Random Pointer
剑指 Offer 35. 复杂链表的复制