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); +};