Copy List with Random Pointer
ID: 105; medium; 复制带随机指针的链表
Solution 1 (Java)
Notes
This solution uses a HashMap to keep track of the original nodes and their duplicates.
For each iteration, we first deal with the node itself. If it is not in the HashMap, we add it to the
map
where the key is itself and the value is its duplicate. If it is in themap
, the next node for the deep copy is its value, i.e., the duplicate in the map. Next, we deal with the random pointers of the node. Using a similar approach, we point the random pointer of the node in the deep copy to a duplicate.Do not forget to update
prev
andhead
. Here,prev
is for constructing the new deep copy andhead
is just for traversing the original linked list.Time complexity is
O(n)
and space complexity is alsoO(n)
.
Scratches
Solution 2 (Java)
Notes
This solution uses three pass to copy the original list. Thus, there are three steps:
copyNext: This step creates new duplicated nodes and point their next pointers to their originals'.
copyRandom: This step simply point the duplicates' random pointers to the corresponding duplicates of their original nodes' random pointers. The key operation here is
head.next.random = head.random.next
. The left is the random pointer of the duplicate and the right is the duplicate of the original random node.splitLists: We cut the connections between the original list and the new deep copy. Be careful with null checking in the loop to prevent
NullPointerException
.
The time complexity is still
O(n)
, but the space complexity now isO(1)
.
Scratches
Last updated