3. What is the output of the following TypeScript code snippet that clones a linked list with random pointers?
class Node {
val: number;
next: Node | null;
random: Node | null;
constructor(val?: number) {
this.val = val ?? 0;
this.next = null;
this.random = null;
}
}
function cloneList(head: Node | null): Node | null {
if (!head) return null;
let curr = head;
while (curr) {
const copy = new Node(curr.val);
copy.next = curr.next;
curr.next = copy;
curr = copy.next;
}
curr = head;
while (curr) {
if (curr.random) curr.next!.random = curr.random.next;
curr = curr.next!.next;
}
curr = head;
const pseudoHead = new Node(0);
let copyCurr = pseudoHead;
while (curr) {
copyCurr.next = curr.next;
curr.next = curr.next!.next;
copyCurr = copyCurr.next;
curr = curr.next;
}
return pseudoHead.next;
}
// Original list: 1 -> 2 -> null
// Node 1 random points to Node 2
// Node 2 random points to Node 1
const node1 = new Node(1);
const node2 = new Node(2);
node1.next = node2;
node1.random = node2;
node2.random = node1;
const clonedHead = cloneList(node1);
console.log(clonedHead!.val);
console.log(clonedHead!.random!.val);
console.log(clonedHead!.next!.val);
console.log(clonedHead!.next!.random!.val);