-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCopyListWithRandomPointer.java
More file actions
38 lines (31 loc) · 995 Bytes
/
CopyListWithRandomPointer.java
File metadata and controls
38 lines (31 loc) · 995 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
package com.company;
import java.util.HashMap;
import java.util.Map;
public class CopyListWithRandomPointer {
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) {
this.label = x;
}
}
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
Map<RandomListNode, RandomListNode> map =
new HashMap<>();
// loop 1. copy all the nodes
RandomListNode node = head;
while (node != null) {
map.put(node, new RandomListNode(node.label));
node = node.next;
}
// loop 2. assign next and random pointers
node = head;
while (node != null) {
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
}