Copy List with Random Pointer
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.
The intuitive approach is to use a hash map to store the mapping between the original nodes and the copied nodes. The following code requires O(2n) in time and O(n) in space.
If we do not want to use extra memory, the following approach could be applied:
The intuitive approach is to use a hash map to store the mapping between the original nodes and the copied nodes. The following code requires O(2n) in time and O(n) in space.
If we do not want to use extra memory, the following approach could be applied:
- Copy the list nodes and insert the copied node right after the original node. For example, A->B->C->... becomes A->copyA->B->copyB->C->copyC->...
- If A has a non-null random pointer, we can simply set A->next->random = A->random->next.
- Split the list into two separate lists.
Comments
Post a Comment