-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy List with Random Pointer.java
More file actions
54 lines (42 loc) · 1.23 KB
/
Copy List with Random Pointer.java
File metadata and controls
54 lines (42 loc) · 1.23 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
42
43
44
45
46
47
48
49
50
51
52
53
54
// 138. Copy List with Random Pointer (https://leetcode.com/problems/copy-list-with-random-pointer/)
import java.util.*;
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
class Solution {
public Node copyRandomList(Node head) {
if (head == null) return null;
Node res = new Node(head.val);
Map<Node, Integer> map = new HashMap<>();
Node[] resNodes = new Node[1001];
Node oriPos = head;
Node resPos = res;
for (int i = 0; oriPos != null; i++) {
map.put(oriPos, i);
resNodes[i] = resPos;
if (oriPos.next != null)
resPos.next = new Node(oriPos.next.val);
oriPos = oriPos.next;
resPos = resPos.next;
}
oriPos = head;
resPos = res;
while (oriPos != null) {
if (map.get(oriPos.random) != null){
int index = map.get(oriPos.random);
resPos.random = resNodes[index];
}
oriPos = oriPos.next;
resPos = resPos.next;
}
return res;
}
}