Give a list of nodes with duplicate values in a sorted singly linked list, we want to remove the duplicates and return distinct ones.
Example:
Input: 1→3→5→5→6→6→7
Output: 1→3→5→6→7
Solution:
Here we will have to pointers. One will keep the current node and one (lets call it runner) will go through the whole list and check for duplicates. Whenever the two pointers point to the same value nodes (duplicates), we will remove the later node by adjusting the next value of the node to it is next of next node and hence deleting the node.
SinglyLinkedListNode RemoveDuplicates(SinglyLinkedListNode head) {
SinglyLinkedListNode current = head;
while(current !=null) {
SinglyLinkedListNode runner = current;
while (runner.next!=null) {
if(runner.next.data == current.data)
runner.next = runner.next.next;
else
runner = runner.next;
}
current = current.next;
}
return head;
}