Remove Duplicates from Sorted Singly Linked List Algo

By   Tewodros   Date Posted: Oct. 12, 2021  Hits: 828   Category:  Algorithm   Total Comment: 0             A+ A-


side

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;

   }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* kkbjff

Back to Top