var copyRandomList = function(head, map = new Map()) {
if (!head) return null;
if (map.has(head)) return map.get(head);
const clone = new Node(head.val);
map.set(head, clone);
clone.next = copyRandomList(head.next, map);
clone.random = copyRandomList(head.random, map);
return clone;
}
var copyRandomList = function(head) {
if (!head) return null;
cloneNode(head);
connectRandomNode(head);
return connectNode(head);
};
const cloneNode = (curr) => {
while (curr) {
const node = new Node(curr.val);
node.next = curr.next;
curr.next = node;
curr = node.next;
}
return curr;
}
const connectRandomNode = (curr) => {
while (curr) {
curr.next.random = curr.random?.next || null;
curr = curr.next.next;
}
}
const connectNode = (head) => {
let [ prev, curr, next ] = [ head, head.next, head.next ];
while (prev) {
prev.next = prev.next.next;
curr.next = curr?.next?.next || null;
prev = prev.next;
curr = curr.next;
}
return next
}