Skip to content

Commit 5dff205

Browse files
committed
Merge pull request neetcode-gh#178 from HangCcZ/main
Added 138-Copy-List-with-Random-Pointer.js
2 parents fc1ac34 + ca10b3a commit 5dff205

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {Node} head
3+
* @return {Node}
4+
*/
5+
var copyRandomList = function (head) {
6+
let map = new Map();
7+
let ptr = head;
8+
9+
while (ptr) {
10+
// map old - new
11+
map.set(ptr, new Node(ptr.val, null, null));
12+
ptr = ptr.next;
13+
}
14+
15+
ptr = head;
16+
while (ptr) {
17+
map.get(ptr).next = map.get(ptr.next) || null;
18+
map.get(ptr).random = map.get(ptr.random) || null;
19+
ptr = ptr.next;
20+
}
21+
return map.get(head);
22+
};

0 commit comments

Comments
 (0)