-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138_CopyListwithRandomPointer.java
71 lines (59 loc) · 1.98 KB
/
138_CopyListwithRandomPointer.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
61
62
63
64
65
66
67
68
69
70
71
// 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.
/**
* 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) {
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode res = head;
while(res != null) {
map.put(res, new RandomListNode(res.label));
res = res.next;
}
res = head;
while(res != null) {
map.get(res).next = map.get(res.next);
res = res.next;
}
res = head;
while(res != null) {
map.get(res).random = map.get(res.random);
res = res.next;
}
return map.get(head);
}
}
//check
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode fakeTargetHead = new RandomListNode(0);
RandomListNode src = head;
RandomListNode target = fakeTargetHead;
while (src!=null) {
RandomListNode node = new RandomListNode(src.label);
map.put(src, node);
target.next = node;
src = src.next;
target = target.next;
}
src = head;
while (src!=null) {
if (null!=src.random) {
RandomListNode node = map.get(src);
RandomListNode to = map.get(src.random);
node.random = to;
}
src = src.next;
}
return fakeTargetHead.next;
}
}