class Node {
val: number;
next: Node | null;
random: Node | null;
constructor(val?: number, next?: Node, random?: Node) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
this.random = random === undefined ? null : random;
}
}
function cloneRandomList(head: Node | null): Node | null {
if (!head) return null;
// Step 1: Insert cloned nodes
let curr = head;
while (curr) {
const clone = new Node(curr.val, curr.next, null);
curr.next = clone;
curr = clone.next;
}
// Step 2: Assign random pointers
curr = head;
while (curr) {
if (curr.random) {
curr.next!.random = curr.random.next;
}
curr = curr.next!.next;
}
// Step 3: Separate lists
curr = head;
const cloneHead = head.next;
while (curr) {
const clone = curr.next!;
curr.next = clone.next;
clone.next = clone.next ? clone.next.next : null;
curr = curr.next;
}
return cloneHead;
}This code clones a linked list with random pointers by interleaving cloned nodes, setting random pointers, and then separating the cloned list.