Clone a Linked List with Next and Random Pointer

hard

You are given the head of a linked list where each node has a next pointer and a random pointer that can point to any node in the list or to null. Construct a deep copy of the list: brand-new nodes whose next and random pointers mirror the original structure, sharing no node object with the original.

Return the head of the copied list.

Input encoding (2 lines): the node values, then the random targets as 0-indexed positions (-1 for null). The judge verifies your copy is disjoint from the original and reports each copied node as val,randomIndex (the index the random pointer lands on within the copy, -1 for null).

Constraints

- The number of nodes is in the range [0, 1000] - -10^4 <= Node.val <= 10^4 - random points to a node in the list or is null

Solve this problem →