Remove all occurrences of duplicates from a sorted Linked List

Given a sorted linked list, delete all nodes that have duplicate numbers (all occurrences), leaving only numbers that appear once in the original list.

Examples:

Input : 23->28->28->35->49->49->53->53
Output : 23->35

Input : 11->11->11->11->75->75
Output : empty List

Note that this is different from Remove Duplicates From Linked List



The idea is to maintain a pointer (prev) to the node which just previous to the block of nodes we are checking for duplicates. In the first example, the pointer prev would point to 23 while we check for duplicates for the node 28. Once we reach the last duplicate node with value 28 (name it current pointer), we can make the next field of prev node to be the next of current and update current=current.next. This would delete the block of nodes with value 28 which has duplicates.

C++

// C++ program to remove all 
// occurrences of duplicates 
// from a sorted linked list.
#include <bits/stdc++.h>
using namespace std;
  
// A linked list node
struct Node
{
    int data;
    struct Node *next;
};
  
// Utility function 
// to create a new Node
struct Node *newNode(int data)
{
Node *temp = new Node;
temp -> data = data;
temp -> next = NULL;
return temp;
}
  
// Function to print nodes 
// in a given linked list.
void printList(struct Node *node)
{
    while (node != NULL)
    {
        printf("%d ", node -> data);
        node = node -> next;
    }
}
  
// Function to remove all occurrences
// of duplicate elements
void removeAllDuplicates(struct Node* &start)
{
    // create a dummy node 
    // that acts like a fake
    // head of list pointing
    // to the original head
    Node* dummy = new Node;
  
    // dummy node points
    // to the original head
    dummy -> next = start;
      
    // Node pointing to last 
    // node which has no duplicate.
    Node* prev = dummy;
      
    // Node used to traverse
    // the linked list.
    Node* current = start;
  
    while(current != NULL)
    {
        // Until the current and 
        // previous values are 
        // same, keep updating current
        while(current -> next != NULL &&
              prev -> next -> data == current -> next -> data)
            current = current -> next;
  
        // if current has unique value 
        // i.e current is not updated, 
        // Move the prev pointer to 
        // next node
        if (prev -> next == current)
            prev = prev -> next;
  
        // when current is updated 
        // to the last duplicate 
        // value of that segment, 
        // make prev the next of current
        else
            prev -> next = current -> next;
  
        current = current -> next;
    }
  
    // update original head to 
    // the next of dummy node 
    start = dummy -> next;
}
  
// Driver Code
int main() 
{
    // 23->28->28->35->49->49->53->53
    struct Node* start = newNode(23);
    start -> next = newNode(28);
    start -> next -> next = newNode(28);
    start -> next -> 
     next -> next = newNode(35);
    start -> next -> 
    next -> next -> next = newNode(49);
    start -> next -> 
    next -> next -> 
    next -> next = newNode(49);
    start -> next -> 
    next -> next -> 
    next -> next -> next = newNode(53);
    start -> next -> 
    next -> next -> 
    next -> next -> 
    next -> next = newNode(53);
    cout << "List before removal " <<
                  "of duplicates\n";
    printList(start);
      
    removeAllDuplicates(start);
      
    cout << "\nList after removal " << 
                   "of duplicates\n";
    printList(start);
    return 0;
}
  
// This code is contributed 
// by NIKHIL JINDAL

Java

/* Java program to remove all occurrences of
   duplicates from a sorted linked list */
  
/* class to create Linked lIst */
class LinkedList
{
    Node head=null; /* head of linked list */
    class Node
    {
        int val; /* value in the node */
        Node next;
        Node(int v)
        {
            /* default value of the next
               pointer field */
            val = v;
            next = null;
        }
    }
  
    /* Function to insert data nodes into
       the Linked List at the front */
    public void insert(int data)
    {
        Node new_node = new Node(data);
        new_node.next = head;
        head = new_node;
    }
  
    /* Function to remove all occurrences
       of duplicate elements */
    public void removeAllDuplicates()
    {
       /* create a dummy node that acts like a fake
          head of list pointing to the original head*/
        Node dummy = new Node(0);
  
        /* dummy node points to the original head*/
        dummy.next = head;
        Node prev = dummy;
        current = head;
  
        while (current != null)
        {
            /* Until the current and previous values
               are same, keep updating current */
            while (current.next != null &&
                   prev.next.val == current.next.val)
                current = current.next;
  
            /* if current has unique value i.e current
                is not updated, Move the prev pointer
                to next node*/
            if (prev.next == current)
                prev = prev.next;
  
            /* when current is updated to the last
               duplicate value of that segment, make
               prev the next of current*/
            else
                prev.next = current.next;
  
            current = current.next;
        }
  
        /* update original head to the next of dummy
           node */
        head = dummy.next;
    }
  
    /* Function to print the list elements */
    public void printList()
    {
        Node trav=head;
        if (head==null)
            System.out.print(" List is empty" );
        while (trav != null)
        {
            System.out.print(trav.val + " ");
            trav = trav.next;
        }
    }
  
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        LinkedList ll = new LinkedList();
        ll.insert(53);
        ll.insert(53);
        ll.insert(49);
        ll.insert(49);
        ll.insert(35);
        ll.insert(28);
        ll.insert(28);
        ll.insert(23);
        System.out.println("Before removal of duplicates");
        ll.printList();
  
        ll.removeAllDuplicates();
  
        System.out.println("\nAfter removal of duplicates");
        ll.printList();
    }
}

Output:

List before removal of duplicates
23 28 28 35 49 49 53 53 
List after removal of duplicates
23 35 

Time Complexity : O(n)

This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Improved By : nik1996

Article Tags :
Practice Tags :



Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.