-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138-copyComplex.java
More file actions
55 lines (48 loc) · 1.22 KB
/
138-copyComplex.java
File metadata and controls
55 lines (48 loc) · 1.22 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
class Node {
public int val;
public Node next;
public Node random;
public Node() {}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
};
class Solution_138 {
public Node copyRandomList(Node head) {
if(head == null) return null;
Node res = copyList(head);
res = copyRandom(res);
res = splitRandom(res);
return res;
}
Node copyList(Node head) {
Node res = head;
while(head != null) {
head.next = new Node(head.val, head.next, null);
head = head.next.next;
}
return res;
}
Node copyRandom(Node head) {
Node res = head;
while(head != null) {
// 随机指针不为空
if(head.random != null) {head.next.random = head.random.next;}
head = head.next.next;
}
return res;
}
Node splitRandom(Node head) {
Node res = new Node(0, null, null);
Node r = res;
while(head != null) {
res.next = head.next;
res = res.next;
head.next = head.next.next;
head = head.next;
}
return r.next;
}
}