-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCopyListWithRandomPointer.java
More file actions
40 lines (37 loc) · 1.2 KB
/
CopyListWithRandomPointer.java
File metadata and controls
40 lines (37 loc) · 1.2 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
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (head == null) {
return null;
}
RandomListNode result = new RandomListNode(0);
RandomListNode rCur = result;
RandomListNode cur = head;
HashMap<Integer, RandomListNode> map = new HashMap<Integer, RandomListNode>();
while (cur != null) {
rCur.next = new RandomListNode(cur.label);
map.put(rCur.next.label, rCur.next);
cur = cur.next;
rCur = rCur.next;
}
cur = head;
rCur = result;
while (cur != null) {
if (cur.random != null) {
rCur.next.random = map.get(cur.random.label);
}
cur = cur.next;
rCur = rCur.next;
}
return result.next;
}
}