Modify a Linked List to contain last occurrences of every duplicate element
Input: 1 -> 2 -> 7 -> 3 -> 2 -> 5 -> 1
Output: 7 -> 3 -> 2 -> 5 -> 1
Given Linked List: 1 -> 2 -> 7 -> 3 -> 2 -> 5 -> 1
Duplicate elements: 1, 2
Modified Linked List: 7 -> 3 -> 2 -> 5 -> 1
Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 1 -> 2 -> 3 -> 4 -> 5
Approach: Follow the steps below to solve the problem:
- Initialize a dummy node and make it’s next point to head.
- Reverse the given Linked List.
- Initialize an unordered set, say visited, to store the already visited nodes.
- Initialize two nodes, say currnode, pointing to the dummy node, and nextnode, to store the next node of the current node.
- Iterate over the linked list and check if data of the next node of the current node is already visited or not.
- If it is already visited, then perform the following steps:
- Initialize a new node, say duplicate, to store the nextnode which is a duplicate node in this case.
- Make current’s next point to next of the nextnode.
- Insert the data of nextnode into the visited set.
- Make nextnode as currentnode.
- Finally, reverse the modified linked list and return.
Below is the implementation of the above approach:
2 3 5 1 6
Time Complexity: O(N)
Auxiliary Space: O(N)
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.