How to remove duplicates from a sorted linked list ?
- To write a removeDuplicates() function which takes a list sorted from the list any duplicate nodes to be deleted. The list should be traversed only once.
Algorithm
- Traverse the head (or start) node from the list. Compare each node with its next node while traversing.
- If same as the current node and data of next node to be delete that node. Before we delete a node, we need to store next pointer of the node.
Implementation
- Functions other than removeDuplicates() are just to create a linked.
- Linked list to be tested and removeDuplicates() from the list.
Sample Code in Java
Time Complexity
- O(n) where n is number of nodes in the given linked list.