15.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.
Last updated
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.
Last updated
Return a deep copy of the list.
Algorithm: 1. Create all nodes in copy linked list using next pointers. 2. Store the next pointer mappings of original linked list. 4. Make the random pointer of copy linked list point to original Linked List. 5. Make the Next pointer of the original Linked List point to copy linked list. 6. Set the random pointer of copy linked list to original values using node->random = node->random->random->next 7.Change next pointer of all nodes in original linked list to point to the corresponding node in linked list.
Time Complexity: O(n) , Space Complexity: O(n)
Algorithm :
Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create a copy of 2 and insert it between 2 & 3. Continue in this fashion, add the copy of N after the Nth node.
Now copy the random link:
Now restore the original and copy linked lists in this fashion in a single loop.
Time Complexity: O(n)