From ca10b3ac7876d81fdf4ae2c17c1b885ac0726d34 Mon Sep 17 00:00:00 2001 From: HangCcz Date: Sat, 16 Apr 2022 20:33:09 -0400 Subject: [PATCH] 138-Copy-List-with-Random-Pointer.js --- .../138-Copy-List-with-Random-Pointer.js | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 javascript/138-Copy-List-with-Random-Pointer.js diff --git a/javascript/138-Copy-List-with-Random-Pointer.js b/javascript/138-Copy-List-with-Random-Pointer.js new file mode 100644 index 000000000..668b38f42 --- /dev/null +++ b/javascript/138-Copy-List-with-Random-Pointer.js @@ -0,0 +1,22 @@ +/** + * @param {Node} head + * @return {Node} + */ +var copyRandomList = function (head) { + let map = new Map(); + let ptr = head; + + while (ptr) { + // map old - new + map.set(ptr, new Node(ptr.val, null, null)); + ptr = ptr.next; + } + + ptr = head; + while (ptr) { + map.get(ptr).next = map.get(ptr.next) || null; + map.get(ptr).random = map.get(ptr.random) || null; + ptr = ptr.next; + } + return map.get(head); +};