-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay5
55 lines (47 loc) · 1.24 KB
/
Day5
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
/*
// 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;
}
Node current = head;
while (current != null) {
Node newNode = new Node(current.val);
newNode.next = current.next;
current.next = newNode;
current = newNode.next;
}
// Step 2: Set random pointers of the new nodes
current = head;
while (current != null) {
if (current.random != null) {
current.next.random = current.random.next;
}
current = current.next.next;
}
// Step 3: Separate the new list from the original list
Node newHead = head.next;
current = head;
while (current != null) {
Node temp = current.next;
current.next = temp.next;
if (temp.next != null) {
temp.next = temp.next.next;
}
current = current.next;
}
return newHead;
}
}