3. Given the following code snippet to clone a linked list with random pointers, what will be the output of the console.log after cloning?
function Node(val) {
this.val = val;
this.next = null;
this.random = null;
}
// Original list: 1 -> 2 -> null
const node1 = new Node(1);
const node2 = new Node(2);
node1.next = node2;
node1.random = node2;
node2.random = node2;
function cloneList(head) {
if (!head) return null;
const map = new Map();
let curr = head;
while (curr) {
map.set(curr, new Node(curr.val));
curr = curr.next;
}
curr = head;
while (curr) {
map.get(curr).next = map.get(curr.next) || null;
map.get(curr).random = map.get(curr.random) || null;
curr = curr.next;
}
return map.get(head);
}
const clonedHead = cloneList(node1);
console.log(clonedHead.val, clonedHead.next.val, clonedHead.random.val);