#K49537. Cloning a Random Pointer Linked List
Cloning a Random Pointer Linked List
Cloning a Random Pointer Linked List
You are given a linked list in which each node contains an integer data, a next
pointer to the next node, and a random
pointer which can point to any node in the list (or be null). Your task is to write a function that creates a deep copy of the linked list such that the new list has exactly the same structure as the original list.
The input is provided for multiple test cases. For each test case, the linked list is represented in a serialized format:
- The first line contains an integer
n
indicating the number of nodes in the list. Ifn = 0
, the list is empty. - If
n > 0
, the second line containsn
integers denoting the node values in order. Thenext
pointers are implicitly defined such that nodei
is connected to nodei+1
for0 ≤ i < n-1
. - The third line contains
n
integers, where each integer is the index (0-indexed) of the node to which therandom
pointer of the corresponding node points. A value of-1
indicates that therandom
pointer is null.
Your function cloneLinkedList
should clone the list and the output should be in the same serialized format as the input for each test case. That is, for each test case, print:
- The integer
n
(the number of nodes in the cloned list). - A line with the node values separated by single spaces.
- A line with the random pointer indices separated by single spaces.
Note: You must read from standard input (stdin) and output to standard output (stdout).
inputFormat
The input begins with an integer T
denoting the number of test cases. For each test case:
- First line contains a single integer
n
representing the number of nodes in the linked list. (Ifn
is 0, the list is empty.) - If
n > 0
, the next line containsn
integers separated by spaces, representing the node values. - The following line contains
n
integers separated by spaces, each representing the index (0-indexed) of the node that therandom
pointer points to, or -1 if it is null.
Input is read from stdin.
outputFormat
For each test case, output the cloned linked list in the same serialized format:
- Print the integer
n
(number of nodes in the cloned list). - Print a line of
n
node values separated by spaces. - Print a line of
n
integers representing the random pointer indices (using 0-indexing, and -1 for null).
Output the result to stdout.
## sample3
0
1
10
-1
3
1 2 3
-1 0 1
0
1
10
-1
3
1 2 3
-1 0 1
</p>