Copy List with Random Pointer
Given a linked list where each node has a val and a random pointer (which can point to any node or null), create a deep copy of the list.
Input: Each node as val,random_index separated by semicolons. Random index -1 means null.
Output: Same format showing the deep copy is correct.
Example
7,-1;13,0;11,4;10,2;1,0
7,-1;13,0;11,4;10,2;1,0
- The input
7,-1;13,0;11,4;10,2;1,0represents a linked list where each node has a value and a random pointer index. The random index-1means the pointer isnull. - We create a deep copy of the list by iterating over each node and assigning a new node with the same
val. Therandompointer of each new node is updated based on the original node'srandomindex. - For the given input, the original list has nodes with values
7,13,11,10, and1. The random pointers are updated as follows:- Node
13points to node7(index0), - Node
11points to node1(index4), - Node
10points to node13(index2).
- Node
- The resulting deep copy has the same node values and random pointer indices, resulting in the output
7,-1;13,0;11,4;10,2;1,0.
Constraints
- 0 <= n <= 1000
- -10^4 <= Node.val <= 10^4
- random_index is -1 or a valid index