-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
32 lines (29 loc) · 944 Bytes
/
Solution.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
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode dummy = new RandomListNode(-1);
RandomListNode d = dummy,
p = head;
Map<RandomListNode, RandomListNode> nodeMap = new HashMap<RandomListNode, RandomListNode>();
while (p != null) {
d.next = new RandomListNode(p.label);
nodeMap.put(p, d.next);
d = d.next;
p = p.next;
}
d = dummy.next;
while (head != null) {
d.random = head.random != null ? nodeMap.get(head.random) : null;
d = d.next;
head = head.next;
}
return dummy.next;
}
}