Problem
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Example 1:
1 |
|
Note:
- You must return the copy of the given head as a reference to the cloned list.
Explanation 1
-
In a normal linked list that each node has a next pointer, on top of it, this problem says each node also has a random pointer that points to other node in the linked list or null. We need to return a copy of this linked list.
-
First, we can create a new result node that has the same value as our input linked list’s head, and use a pointer
resPtr
pointing to it. Then starts from the second node using a pointercur
, use this pointer iterate the input linked list, andresPtr.next
set to a new node that has the same value as the node thatcur
points at. This way, we can copy the normal linked list but not the random pointer. Also in each iteration, we can create a hashmap to map acur
pointer to its node because we don’t want to map result’s randome node to linked list’s random noderes.random = cur.random
, we want to map result’s random node to result’s node, not input linked list’s noderes.random = randomResNode
. (remember to map the first node because we start iterating from the second nodemap.put(head, res)
, key is the original linkedlist node, value is the result node). -
After the first iteration, we got the copy of the normal linked list. Now we iterate this linked list again, to link the random pointer by using
resPtr.random = map.get(curPtr);
.
Solution 1
1 |
|
Explanation 2
- In the above method, we used hashmap that costs extra space. This method can save space.
- First, we copy a new node behind each node.
- Then, we can assign new node’s random pointer by doing
cur.next.random = cur.random.next
. - Finally, we can cut off the original node and copied node’s list.
Solution 2
1 |
|