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
- 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
- Delete a Node from linked list without head pointer
- Select a Random Node from a Singly 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
- How to write C functions that modify head pointer of a Linked List?
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Given only a pointer/reference 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
- 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
- Difference between Singly linked list and Doubly linked list