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
- Delete a Node from linked list without head pointer
- How to write C functions that modify head pointer of a Linked List?
- Point to next higher value node in a linked list with an arbitrary pointer
- 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?
- Point arbit pointer to greatest value right side node in a linked list
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Select a Random Node from a Singly Linked List
- Clone a Binary Tree with Random Pointers
- Create new linked list from two given linked list with greater element at each node
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Merge a linked list into another linked list at alternate positions
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- Check if a linked list is Circular Linked List
Improved By : andrew1234