-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyListWithRandomPointer.java
More file actions
41 lines (35 loc) · 1.12 KB
/
Copy pathCopyListWithRandomPointer.java
File metadata and controls
41 lines (35 loc) · 1.12 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
import java.util.HashMap;
import java.util.Map;
/**
* A linked list is given such that each node contains an additional random pointer which could point to any node in the
* list or null.
*
* Return a deep copy of the list.
*
* @author JoshLuo
*
*/
public class CopyListWithRandomPointer {
// BFS
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return head;
}
Map<RandomListNode, RandomListNode> oldToNew = new HashMap<RandomListNode, RandomListNode>();
oldToNew.put(head, new RandomListNode(head.label));
RandomListNode runner = head;
while (runner.next != null) {
oldToNew.put(runner.next, new RandomListNode(runner.next.label));
oldToNew.get(runner).next = oldToNew.get(runner.next);
runner = runner.next;
}
runner = head;
while (runner != null) {
if (runner.random != null) {
oldToNew.get(runner).random = oldToNew.get(runner.random);
}
runner = runner.next;
}
return oldToNew.get(head);
}
}