![]() |
VOOZH | about |
Given an unsorted linked list containing n nodes, the task is to remove duplicate nodes while preserving the original order.
Examples:
Input: 12 -> 11 -> 12 -> 21 -> 41 -> 43 -> 21
Output: 12 -> 11 -> 21 -> 41 -> 43
Explanation: The second occurrence of 12 (the one after 11) and the second occurrence of 21 (the one at the end) are removed, resulting in a linked list that maintains the order of their first appearances.Input:1 -> 2 -> 3 -> 2 -> 4
Output: 1 -> 2 -> 3 -> 4
Explanation: Similarly, the second occurrence of 2 is removed, ensuring that each number appears only once while maintaining the order of their first appearances.
Table of Content
The idea is to use two loops to remove duplicates from an unsorted linked list. The first loop goes through each node one by one. For each node, the second loop checks all the nodes that come after it to see if there are any duplicates. If a duplicate is found, it removes it by changing the links. This way, we keep only the first occurrence of each number while maintaining their order.
12 11 21 41 43
In this approach, we can use a hash set to keep track of the values (nodes) that have already been seen. As we traverse the linked list, for each node, we check if its value is already in the hash set. If the value is found, it means it's a duplicate, so we remove that node by adjusting the pointers of the previous node to skip the current one. If the value is not found, we add it to the hash set and move to the next node.
12 11 21 41 43