Java Program For Cloning A Linked List With Next And Random Pointer- Set 2
We have already discussed 2 different ways to clone a linked list. In this post, one more simple method to clone a linked list is discussed.
The idea is to use Hashing. Below is algorithm.
- Traverse the original linked list and make a copy in terms of data.
- Make a hash map of key value pair with original linked list node and copied linked list node.
- Traverse the original linked list again and using the hash map adjust the next and random reference of cloned linked list nodes.
Below is the implementation of above approach.
Original linked list Data = 1, Random data = 3 Data = 2, Random data = 4 Data = 3, Random data = 5 Data = 4, Random data = -1 Data = 5, Random data = 2 Cloned linked list Data = 1, Random data = 3 Data = 2, Random data = 4 Data = 3, Random data = 5 Data = 4, Random data = -1 Data = 5, Random data = 2
Time complexity: O(n)
Auxiliary space: O(n)
Please refer complete article on Clone a linked list with next and random pointer | Set 2 for more details!
My Personal Notes arrow_drop_up
Please Login to comment...