Copy List with Random Pointer
MediumLinked List
You are given the head of a linked list of length n in which every node has two pointers:
next, which points to the following node (orNoneat the tail), andrandom, which can point to any node in the list, including the node itself, or beNone.
Return the head of a deep copy of the list: n brand-new nodes with the same values, where each copy's next and random point to the corresponding *copied* nodes. No pointer in the copy may refer to a node of the original list, and the original list must be left unchanged when you return.
How lists are written: in the examples, a list is shown as an array of [val, random_index] pairs from head to tail, where random_index is the 0-based position of the node that random points to, or None. The node class is:
python
class Node:
def __init__(self, x, next=None, random=None):
self.val = x
self.next = next
self.random = randomExample 1
- Input:
- head = [[4, 2], [9, None], [6, 0], [1, 1]]
- Output:
- [[4, 2], [9, None], [6, 0], [1, 1]]
- Explanation
- Node 0 (value 4) has a random pointer forward to node 2, node 2 points back to node 0, node 3 points to node 1, and node 1 has none. The copy must have the same values and the same random targets, but every pointer must lead to copied nodes.
Example 2
- Input:
- head = [[7, 0]]
- Output:
- [[7, 0]]
- Explanation
- A single node whose random pointer is itself. In the copy, the new node's random pointer must point to the new node, not to the original.
Example 3
- Input:
- head = [[2, 1], [2, 0]]
- Output:
- [[2, 1], [2, 0]]
- Explanation
- Both nodes hold the value 2, so random targets cannot be found by matching values. Each copied node must point to the copy of the other one.
Constraints
0 <= n <= 1000-10^4 <= Node.val <= 10^4Node.randomisNoneor points to a node in the list