-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138.copy-list-with-random-pointer.java
52 lines (47 loc) · 1.34 KB
/
138.copy-list-with-random-pointer.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
/*
* @lc app=leetcode id=138 lang=java
*
* [138] Copy List with Random Pointer
*/
// @lc code=start
/*
// 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;
}
// 1. For each node S, we create new node S' and insert it right before S
// A -> B -> C ==> A -> A' -> B -> B' -> C -> C'
for (Node node = head; node != null; node = node.next.next) {
Node nodeNew = new Node(node.val);
nodeNew.next = node.next;
node.next = nodeNew;
}
// 2. Thus, we can get nodeNew.random by node.random.next
for (Node node = head; node != null; node = node.next.next) {
Node nodeNew = node.next;
nodeNew.random = (node.random != null) ? node.random.next : null;
}
// 3. Detach 2 lists
Node headNew = head.next;
for (Node node = head; node != null; node = node.next) {
Node nodeNew = node.next;
node.next = node.next.next;
nodeNew.next = (nodeNew.next != null) ? nodeNew.next.next : null;
}
return headNew;
}
}
// @lc code=end