forked from rubythonode/javascript-problems-and-solutions
-
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 (40 loc) · 946 Bytes
/
copy-list-with-random-pointer.js
File metadata and controls
47 lines (40 loc) · 946 Bytes
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
/**
* Copy List with Random Pointer
*
* A linked list is given such that each node contains an additional random pointer
* which could point to any node in the list or null.
*
* Return a deep copy of the list.
*/
/**
* Definition for singly-linked list with a random pointer.
* function RandomListNode(label) {
* this.label = label;
* this.next = this.random = null;
* }
*/
/**
* @param {RandomListNode} head
* @return {RandomListNode}
*/
const copyRandomList = head => {
if (!head) {
return null;
}
const map = new Map();
// Step 1. Copy all the nodes
let p = head;
while (p) {
map.set(p, new RandomListNode(p.label));
p = p.next;
}
// Step 2. Copy the next and random pointers
p = head;
while (p) {
if (p.next) map.get(p).next = map.get(p.next);
if (p.random) map.get(p).random = map.get(p.random);
p = p.next;
}
return map.get(head);
};
export { copyRandomList };