-
Notifications
You must be signed in to change notification settings - Fork 2
/
CopyList138.java
60 lines (52 loc) · 1.43 KB
/
CopyList138.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package linkedList;
import java.util.HashMap;
import java.util.Map;
class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) {
this.label = x;
}
};
public class CopyList138 {
private Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return head;
if (map.get(head) != null)
return map.get(head);
RandomListNode newHead = new RandomListNode(head.label);
map.put(head, newHead);
newHead.next = copyRandomList(head.next);
newHead.random = copyRandomList(head.random);
return newHead;
}
public RandomListNode copyRandomListV2(RandomListNode head) {
if (head == null)
return head;
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode iter = head;
while (iter != null) {
map.put(iter, new RandomListNode(iter.label));
iter = iter.next;
}
iter = head;
while (iter != null) {
if (iter.next != null) {
map.get(iter).next = map.get(iter.next);
}
if (iter.random != null) {
map.get(iter).random = map.get(iter.random);
}
iter = iter.next;
}
return map.get(head);
}
public static void main(String[] args) {
RandomListNode head = new RandomListNode(-1);
RandomListNode node1 = new RandomListNode(1);
head.next = node1;
head.random = node1;
new CopyList138().copyRandomList(head);
}
}