
A linked list where each node has a val, a next pointer, and a random pointer that can point to any node in the list or null. Return a deep copy of the list — every node must be a new object, with the same val, next, and random structure as the original.
Constraints:
random may point to any node or be null.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 copyRandomList(head: _Node | null): _Node | null {
let nodes = new Map<_Node, _Node>()
let currentOld: _Node | null = head
while (currentOld) {
nodes.set(currentOld, new _Node(currentOld.val))
currentOld = currentOld.next
}
currentOld = head
while (currentOld) {
let newNode: _Node = nodes.get(currentOld)!
if(currentOld.random) {
newNode.random = nodes.get(currentOld.random)!
}
if (currentOld.next) {
newNode.next = nodes.get(currentOld.next)!
}
currentOld = currentOld.next
}
return nodes.get(head!)!
};