-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-list-with-random-pointer.js
More file actions
47 lines (42 loc) · 1.01 KB
/
copy-list-with-random-pointer.js
File metadata and controls
47 lines (42 loc) · 1.01 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
/**
* Definition for a Node.
* function Node(val, next, random) {
* this.val = val;
* this.next = next;
* this.random = random;
* }
*/
/**
* @param {Node} head
* @return {Node}
*/
var copyRandomList = function (head) {
if (!head) return null;
// Step 1: Create a copy of each node and link them next to the original node
let current = head;
while (current) {
const newNode = new Node(current.val, current.next, null);
current.next = newNode;
current = newNode.next;
}
// Step 2: Set the random pointers of the newly created nodes
current = head;
while (current) {
if (current.random) {
current.next.random = current.random.next;
}
current = current.next.next;
}
// Step 3: Separate the original list and the copied list
current = head;
const newHead = head.next;
while (current) {
const copy = current.next;
current.next = copy.next;
current = current.next;
if (current) {
copy.next = current.next;
}
}
return newHead;
};