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.
1. Traverse the original linked list and make a copy in terms of data.
2. Make a hash map of key value pair with original linked list node and copied linked list node.
3. 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)
This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Clone a linked list with next and random pointer | Set 1
- Clone a linked list with next and random pointer in O(1) space
- Correct the Random Pointer in Doubly Linked List
- Insertion in a sorted circular linked list when a random pointer is given
- Point to next higher value node in a linked list with an arbitrary pointer
- Clone a Binary Tree with Random Pointers
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- How to write C functions that modify head pointer of a Linked List?
- Point arbit pointer to greatest value right side node in a linked list
- Delete multiple occurrences of key in Linked list using double pointer
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Delete a Node from linked list without head pointer
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Select a Random Node from a Singly Linked List
- Sum of nodes in a linked list which are greater than next node
- Next greater element in the Linked List
- Difference between Singly linked list and Doubly linked list
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list