-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopyListWithRandomPointer.java
More file actions
84 lines (69 loc) · 2.15 KB
/
CopyListWithRandomPointer.java
File metadata and controls
84 lines (69 loc) · 2.15 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package leetcode;
import utils.Node;
import java.util.HashMap;
import java.util.Map;
/**
* CopyListWithRandomPointer
* https://leetcode-cn.com/problems/copy-list-with-random-pointer/
* 138. 复制带随机指针的链表
* https://leetcode-cn.com/problems/copy-list-with-random-pointer/solution/liang-ge-mapjie-ti-by-oshdyr-hy1i/
* 思路:
* 1. 直接索引;
* 2. 借助栅栏, 位置偏移关系立即可查, 取代索引;
*
* @author tobin
* @since 2021-07-22
*/
public class CopyListWithRandomPointer {
public static void main(String[] args) {
Node head = new Node(0);
for (int i = 1; i < 5; i++) {
Node tmp = head;
head = new Node(i);
head.next = tmp;
}
Node tmp = head;
while (tmp != null) {
System.out.println(tmp.val);
tmp = tmp.next;
}
CopyListWithRandomPointer sol = new CopyListWithRandomPointer();
Node newHead = sol.copyRandomList(head);
Node newTmp = newHead;
while (newTmp != null) {
System.out.println(newTmp.val);
newTmp = newTmp.next;
}
}
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
Map<Node, Integer> oldValue2Index = new HashMap<>();
Map<Integer, Node> index2NewValue = new HashMap<>();
Node newHead = new Node(head.val);
oldValue2Index.put(head, 0);
index2NewValue.put(0, newHead);
Node next = head;
Node newNext = newHead;
int idx = 1;
while (next.next != null) {
newNext.next = new Node(next.next.val);
oldValue2Index.put(next.next, idx);
index2NewValue.put(idx, newNext.next);
next = next.next;
newNext = newNext.next;
idx++;
}
Node tmp = head;
Node newTmp = newHead;
while (tmp != null) {
if (tmp.random != null) {
newTmp.random = index2NewValue.get(oldValue2Index.get(tmp.random));
}
tmp = tmp.next;
newTmp = newTmp.next;
}
return newHead;
}
}