Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Remove Duplicates from an Unsorted Linked List
Next article icon

Remove all occurrences of duplicates from a sorted Linked List

Last Updated : 10 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Recommended Practice
Remove all occurences of duplicates in a linked list
Try It!

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 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.

Implementation:

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) {         cout<<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 Aditya Kumar (adityakumar129) 
C
// C++ program to remove all // occurrences of duplicates // from a sorted linked list. #include<stdio.h> #include<stdlib.h>  // A linked list node typedef struct Node {     int data;     struct Node* next; }Node;  // Utility function // to create a new Node struct Node* newNode(int data) {     Node* temp = (Node *)malloc(sizeof(Node));     temp->data = data;     temp->next = NULL;     return temp; }  // Function to print nodes // in a given linked list. void printList(Node* node) {     while (node != NULL) {         printf("%d ", node->data);         node = node->next;     } }  // Function to remove all occurrences // of duplicate elements void removeAllDuplicates(Node* start) {     // create a dummy node     // that acts like a fake     // head of list pointing     // to the original head     Node* dummy = (Node *)malloc(sizeof(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);     printf("List before removal of duplicates\n");     printList(start);      removeAllDuplicates(start);      printf("\nList after removal of duplicates\n");     printList(start);     return 0; }  // This code is contributed by Aditya Kumar (adityakumar129) 
Java
// Java program to remove all occurrences of // duplicates from a sorted linked list   // class to create Linked lIst  class LinkedList{      // head of linked list  Node head = null;  class Node {          // value in the node      int val;      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;     Node 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 code 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(); } } 
Python3
# Python3 implementation for the above approach  # Creating node class Node:     def __init__(self, val):         self.val = val         self.next = None class LinkedList:     def __init__(self):         self.head = None              # add node into beginning of linked list     def push(self, new_data):         new_node = Node(new_data)         new_node.next = self.head         self.head = new_node         return new_node              # Function to remove all occurrences     # of duplicate elements     def removeAllDuplicates(self, temp):                  # temp is head node of linkedlist         curr = temp         # print(' print something')         head = prev = Node(None)         head.next = curr          # Here we use same as we do in removing          # duplicates and only extra thing is that         # we need to remove all elements          # having duplicates that we did in 30-31         while curr and curr.next:                          # until the current value and next              # value are same keep updating the current value             if curr.val == curr.next.val:                 while(curr and curr.next and                        curr.val == curr.next.val):                     curr = curr.next                                          # still one of duplicate values left                     # so point prev to curr                 curr = curr.next                 prev.next = curr             else:                 prev = prev.next                 curr = curr.next         return head.next              # for print the linkedlist     def printList(self):         temp1 = self.head         while temp1 is not None:             print(temp1.val, end = " ")             temp1 = temp1.next                  # For getting head of linkedlist     def get_head(self):         return self.head  # Driver Code if __name__=='__main__':     llist = LinkedList()     llist.push(53)     llist.push(53)     llist.push(49)     llist.push(49)     llist.push(35)     llist.push(28)     llist.push(28)     llist.push(23)          print('Created linked list is:')     llist.printList()     print('\nLinked list after deletion of duplicates:')     head1 = llist.get_head()     #print(head1)     llist.removeAllDuplicates(head1)     llist.printList()          # This code is contributed  # by PRAVEEN KUMAR(IIIT KALYANI) 
C#
/* C# program to remove all occurrences of duplicates from a sorted linked list */  using System;  /* class to create Linked lIst */ public class LinkedList {     Node head = null; /* head of linked list */     class Node     {         public int val; /* value in the node */         public Node next;         public 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;         Node 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)             Console.Write(" List is empty" );         while (trav != null)         {             Console.Write(trav.val + " ");             trav = trav.next;         }     }      /* Driver code */     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);         Console.WriteLine("Before removal of duplicates");         ll.printList();          ll.removeAllDuplicates();          Console.WriteLine("\nAfter removal of duplicates");         ll.printList();     } }  // This code is contributed by Rajput-Ji 
JavaScript
// Remove all occurrences of duplicates from a sorted Linked List  class Node {     constructor(val, next = null) {         this.data = val;         this.next = next;     }  }  const node1 = new Node(11); const node2 = new Node(11); const node3 = new Node(11); const node4 = new Node(75); const node5 = new Node(75); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5;  const removeDuplicate = (head) => {     let current = head;     let prev = null;     while(current) {         if (current.next && current.data == current.next.data) {            let pivot = current;            let newCurrent = current.next            while (newCurrent && pivot.data === newCurrent.data) {                // removing current;                pivot.next = newCurrent.next;                // increment                newCurrent = newCurrent.next;            }            // removing first duplicate element            if (prev) prev.next = pivot.next;            else head = pivot.next                        current = pivot.next         } else {             prev = current;             current = current.next;         }     }     return head; }  console.log(JSON.stringify(removeDuplicate(node1))); 

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)
Auxiliary Space: O(1) because extra space is not required in removal of duplicates

 


Next Article
Remove Duplicates from an Unsorted Linked List

S

Saloni Baweja
Improve
Article Tags :
  • Linked List
  • DSA
Practice Tags :
  • Linked List

Similar Reads

  • Remove duplicates from a sorted linked list
    Given a linked list sorted in non-decreasing order. Return the list by deleting the duplicate nodes from the list. The returned list should also be in non-decreasing order. Example: Input : Linked List = 11->11->11->21->43->43->60Output : 11->21->43->60Explanation: Input :
    15+ min read
  • Javascript Program For Removing 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->53Output: 23->35Input: 11->11->11->11->75->75Output: empty ListN
    3 min read
  • Remove duplicates from a sorted linked list using recursion
    Write a removeDuplicates() function which takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list
    8 min read
  • Remove Duplicates from an Unsorted Linked List
    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 afte
    14 min read
  • Remove duplicates from a sorted doubly linked list
    Given a sorted doubly linked list containing n nodes. The problem is removing duplicate nodes from the given list. Examples: Algorithm: removeDuplicates(head_ref, x) if head_ref == NULL return Initialize current = head_ref while current->next != NULL if current->data == current->next->da
    12 min read
  • Remove duplicates from an unsorted doubly linked list
    Given an unsorted doubly linked list containing n nodes, the task is to remove duplicate nodes while preserving the original order. Examples: Input: Doubly Linked List = 1 <-> 2 <-> 3 <-> 2 <-> 4Output: Doubly Linked List = 1 <-> 2 <-> 3 <-> 4 Input: Doubly
    15 min read
  • Javascript Program For Removing Duplicates From A Sorted Linked List
    Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
    8 min read
  • Javascript Program For Removing Duplicates From An Unsorted Linked List
    Given an unsorted Linked List, the task is to remove duplicates from the list. Examples: Input: linked_list = 12 -> 11 -> 12 -> 21 -> 41 -> 43 -> 21 Output: 12 -> 11 -> 21 -> 41 -> 43 Explanation: Second occurrence of 12 and 21 are removed. Input: linked_list = 12 ->
    5 min read
  • Remove all the Even Digit Sum Nodes from a Doubly Linked List
    Given a Doubly linked list containing N nodes, the task is to remove all the nodes from the list which contains elements whose digit sum is even. Examples: Input: DLL = 18 <=> 15 <=> 8 <=> 9 <=> 14 Output: 18 <=> 9 <=> 14 Explanation: The linked list contains : 18
    13 min read
  • Remove all occurrences of one Linked list in another Linked list
    Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences