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 doubly linked list
Next article icon

Remove duplicates from a sorted linked list

Last Updated : 26 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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->60
Output : 11->21->43->60
Explanation:

Remove-duplicates-from-a-sorted-linked-list

Remove duplicates from a sorted linked list

Input : Linked List = 5->10->10->20
Output : 5->10->20 (After removing duplicate elements)

[Naive Approach] Remove duplicates using HashSet – O(n) Time and O(n) Space:

The idea is to traverse the linked list and check if the value is present in HashSet or not. If the value is not present in the HashSet then push the value in HashSet append the nodes in the new list , otherwise skip the value as it is the duplicate value.

Follow the steps below to solve the problem:

  • Initialize an empty HashSet and pointers new_head and tail as NULL.
  • Iterate through the original list, adding each unique node’s value to the HashSet and appending the node to the new list.
  • Return the new_head of the new list with duplicates removed.

Below is the implementation of the above approach:

C++
// C++ Program to remove duplicates from a // sorted linked list using Hashset  #include <bits/stdc++.h> using namespace std;  class Node {   public:     int data;     Node *next;     Node(int x) {         data = x;         next = nullptr;     } };  Node *removeDuplicates(Node *head) {        // Unordered map to track unique node values     unordered_set<int>st;      // Initialize pointers for traversing the original list     // and building the new list without duplicates     Node *new_head = nullptr;     Node *tail = nullptr;      // Traverse the original list     Node *curr = head;     while (curr != nullptr) {                // Check if the current node's data is not in the map         if (st.find(curr->data) == st.end()) {                        // Create a new node for the unique data             Node *new_node = new Node(curr->data);              // If new_head is null, this is the             // first unique node             if (new_head == nullptr) {                 new_head = new_node;                 tail = new_head;             }             else {                 // Append the new node to the end                 // of the new list                 tail->next = new_node;                 tail = new_node;             }              // Mark this data as encountered             st.insert(curr->data);         }                // Move to the next node in the original list         curr = curr->next;     }        // Return the head of the new list with     // duplicates removed     return new_head; }  void printList(Node *node) {     while (node != NULL) {         cout << node->data << " ";         node = node->next;     }     cout << endl; }  int main() {        // Create a sorted linked list     // 11->11->11->13->13->20     Node *head = new Node(11);     head->next = new Node(11);     head->next->next = new Node(11);     head->next->next->next = new Node(13);     head->next->next->next->next = new Node(13);     head->next->next->next->next->next = new Node(20);      cout << "Linked list before duplicate removal:" << endl;     printList(head);      head = removeDuplicates(head);      cout << "Linked list after duplicate removal:" << endl;     printList(head);      return 0; } 
Java
// Java program to remove duplicates from a // sorted linked list using Hashset  import java.io.*; import java.util.HashSet;  class Node {     int data;     Node next;     Node(int x) {         data = x;         next = null;     } }  class GfG {        // Function to remove duplicates     static Node removeDuplicates(Node head) {                // HashSet to track unique node values         HashSet<Integer> st = new HashSet<>();          // Initialize pointers for traversing         // the original list and building the new         // list without duplicates         Node temp = head;         Node newHead = null;         Node tail = null;          // Traverse the original list         while (temp != null) {                        // Check if the current node's data is not in             // the set             if (!st.contains(temp.data)) {                                // Create a new node for the unique data                 Node newNode = new Node(temp.data);                  // If newHead is null, this is the first                 // unique node                 if (newHead == null) {                     newHead = newNode;                     tail = newHead;                 }                 else {                     // Append the new node to the                     // end of the new list                     tail.next = newNode;                     tail = newNode;                 }                  // Mark this data as encountered                 st.add(temp.data);             }             // Move to the next node in the original list             temp = temp.next;         }                // Return the head of the new list with         // duplicates removed         return newHead;     }      // Function to print nodes in a given linked list     public static void printList(Node node) {         while (node != null) {             System.out.print(node.data + " ");             node = node.next;         }         System.out.println();     }      public static void main(String[] args) {                // Create a sorted linked list:         // 11->11->11->13->13->20         Node head = new Node(11);         head.next = new Node(11);         head.next.next = new Node(11);         head.next.next.next = new Node(13);         head.next.next.next.next = new Node(13);         head.next.next.next.next.next = new Node(20);          System.out.println(             "Linked list before duplicate removal:");         printList(head);          head = removeDuplicates(head);          System.out.println(             "Linked list after duplicate removal:");         printList(head);     } } 
Python
# Python3 program to remove duplicate # nodes from a sorted linked list using Hashset  class Node:     def __init__(self, x):         self.data = x         self.next = None   def remove_duplicates(head):    # Set to track unique node values     st = set()      # Initialize pointers for traversing     # the original list and building the      # new list without duplicates     temp = head     new_head = None     tail = None      # Traverse the original list     while temp:          # Check if the current node's data         # is not in the set         if temp.data not in st:              # Create a new node for the unique data             new_node = Node(temp.data)              # If new_head is None, this is the              #first unique node             if new_head is None:                 new_head = new_node                 tail = new_head             else:                 # Append the new node to the end                 #of the new list                 tail.next = new_node                 tail = new_node              # Mark this data as encountered             st.add(temp.data)          # Move to the next node in the original list         temp = temp.next      # Return the head of the new list with     #duplicates removed     return new_head   def print_list(node):     while node:         print(node.data, end=" ")         node = node.next     print()   if __name__ == "__main__":        # Create a sorted linked list:     # 11->11->11->13->13->20     head = Node(11)     head.next = Node(11)     head.next.next = Node(11)     head.next.next.next = Node(13)     head.next.next.next.next = Node(13)     head.next.next.next.next.next = Node(20)      print("Linked list before duplicate removal:")     print_list(head)      head = remove_duplicates(head)      print("Linked list after duplicate removal:")     print_list(head) 
C#
// C# program to remove duplicates // from a sorted linked list using hashSet  using System; using System.Collections.Generic;  public class Node {     public int data;     public Node next;     public Node(int x) {         data = x;         next = null;     } }  class GfG {        // Function to remove duplicates     static Node RemoveDuplicates(Node head) {                // HashSet to track unique node values         HashSet<int> st = new HashSet<int>();          // Initialize pointers for traversing the original         // list and building the new list without duplicates         Node temp = head;         Node newHead = null;         Node tail = null;          // Traverse the original list         while (temp != null) {                        // Check if the current node's data             // is not in the set             if (!st.Contains(temp.data)) {                                // Create a new node for the unique data                 Node newNode = new Node(temp.data);                  // If newHead is null, this is the                 // first unique node                 if (newHead == null) {                     newHead = newNode;                     tail = newHead;                 }                 else {                     // Append the new node to the end                     // of the new list                     tail.next = newNode;                     tail = newNode;                 }                  // Mark this data as encountered                 st.Add(temp.data);             }             // Move to the next node in the           	//original list             temp = temp.next;         }         // Return the head of the new list         return newHead;     }      static void PrintList(Node node) {         while (node != null) {             Console.Write(node.data + " ");             node = node.next;         }         Console.WriteLine();     }      static void Main() {                // Create a sorted linked list:         //11->11->11->13->13->20         Node head = new Node(11);         head.next = new Node(11);         head.next.next = new Node(11);         head.next.next.next = new Node(13);         head.next.next.next.next = new Node(13);         head.next.next.next.next.next = new Node(20);          Console.WriteLine(             "Linked list before duplicate removal:");         PrintList(head);                head = RemoveDuplicates(head);          Console.WriteLine(             "Linked list after duplicate removal:");         PrintList(head);     } } 
JavaScript
// JavaScript program to remove duplicates // from a sorted linked list using hashSet  class Node {     constructor(x) {         this.data = x;         this.next = null;     } }  function removeDuplicates(head) {      // Set to track unique node values     const st = new Set();      // Initialize pointers for traversing the original list     // and building the new list without duplicates     let temp = head;     let newHead = null;     let tail = null;      // Traverse the original list     while (temp !== null) {              // Check if the current node's         // data is not in the set         if (!st.has(temp.data)) {                      // Create a new node for the unique data             const newNode = new Node(temp.data);              // If newHead is null, this is the first             // unique node             if (newHead === null) {                 newHead = newNode;                 tail = newHead;             }             else {                 // Append the new node to the end of                 // the new list                 tail.next = newNode;                 tail = newNode;             }              // Mark this data as encountered             st.add(temp.data);         }         // Move to the next node in the original list         temp = temp.next;     }          // Return the head of the new list with     // duplicates removed     return newHead; }  function printList(node) {     let current = node;     while (current) {         process.stdout.write(current.data + " ");         current = current.next;     }     console.log(); }  // Create a sorted linked list: // 11->11->11->13->13->20 let head = new Node(11); head.next = new Node(11); head.next.next = new Node(11); head.next.next.next = new Node(13); head.next.next.next.next = new Node(13); head.next.next.next.next.next = new Node(20);  console.log("Linked list before duplicate removal:"); printList(head);  head = removeDuplicates(head);  console.log("Linked list after duplicate removal:"); printList(head); 

Output
Linked list before duplicate removal: 11 11 11 13 13 20  Linked list after duplicate removal: 11 13 20  

Time Complexity: O(n)  where n is the number of nodes in the given linked list.
Auxiliary Space: O(n) 

[Expected Approach] By Changing Next Pointer – O(n) Time and O(1) Space:

The idea is to traverse the linked list and for each node, if the next node has the same data, skip and delete the duplicate node.

Follow the steps below to solve the problem:

  • Traverse the linked list starting from the head node.
  • Iterate through the list, comparing each node with the next node.
    • If the data in the next node is same as the curr node adjust pointers to skip the next node.

Below is the implementation of the above approach: 

C++
// C++ Program to remove duplicates from a // sorted linked list  #include <bits/stdc++.h> using namespace std;  class Node {   public:     int data;     Node *next;     Node(int x) {         data = x;         next = nullptr;     } };   Node *removeDuplicates(Node *head) {     Node *curr = head;      // Traverse the list     while (curr != NULL && curr->next != NULL) {                // Check if next value is same as current         if (curr->data == curr->next->data) {             Node *next_next = curr->next->next;             curr->next = next_next;         }         else             curr = curr->next;     }     return head; }  void printList(Node *node) {     while (node != NULL) {         cout << node->data << " ";         node = node->next;     }     cout << endl; }  int main() {        // Create a sorted linked list     // 11->11->11->13->13->20     Node *head = new Node(11);     head->next = new Node(11);     head->next->next = new Node(11);     head->next->next->next = new Node(13);     head->next->next->next->next = new Node(13);     head->next->next->next->next->next = new Node(20);      cout << "Linked list before duplicate removal:" << endl;     printList(head);      head = removeDuplicates(head);      cout << "Linked list after duplicate removal:" << endl;     printList(head);      return 0; } 
C
// C Program to remove duplicates from a  // sorted linked list #include <stdio.h>  struct Node {     int data;     struct Node *next; };  // Function to remove duplicates struct Node *removeDuplicates(struct Node *head) {     struct Node *curr = head;      // Traverse the list     while (curr != NULL && curr->next != NULL) {                // Check if next value is the same as curr         if (curr->data == curr->next->data) {             struct Node *next_next = curr->next->next;             curr->next = next_next;         }         else             curr = curr->next;     }     return head; }  void printList(struct Node *node) {     while (node != NULL) {         printf("%d ", node->data);         node = node->next;     }     printf("\n"); }  struct Node *createNode(int new_data){     struct Node *new_node =       (struct Node *)malloc(sizeof(struct Node));     new_node->data = new_data;     new_node->next = NULL;     return new_node; }  int main() {        // Create a sorted linked list:     // 11->11->11->13->13->20     struct Node *head = createNode(11);     head->next = createNode(11);     head->next->next = createNode(11);     head->next->next->next = createNode(13);     head->next->next->next->next = createNode(13);     head->next->next->next->next->next = createNode(20);      printf("Linked list before duplicate removal:\n");     printList(head);      head = removeDuplicates(head);      printf("Linked list after duplicate removal:\n");     printList(head);      return 0; } 
Java
// Java program to remove duplicates // from a sorted linked list import java.io.*;  class Node {     int data;     Node next;     Node(int x) {         data = x;         next = null;     } }  class GfG {        // Function to remove duplicates     static Node removeDuplicates(Node head) {         Node curr = head;          // Traverse the list         while (curr != null && curr.next != null) {                        // Check if next value is the same as curr             if (curr.data == curr.next.data) {                 Node nextNext = curr.next.next;                 curr.next = nextNext;             }             else {                 curr = curr.next;             }         }         return head;     }      static void printList(Node node) {         while (node != null) {             System.out.print(node.data + " ");             node = node.next;         }         System.out.println();     }      public static void main(String[] args) {                // Create a sorted linked list:         // 11->11->11->13->13->20         Node head = new Node(11);         head.next = new Node(11);         head.next.next = new Node(11);         head.next.next.next = new Node(13);         head.next.next.next.next = new Node(13);         head.next.next.next.next.next = new Node(20);          System.out.println(             "Linked list before duplicate removal:");         printList(head);          head = removeDuplicates(head);          System.out.println(             "Linked list after duplicate removal:");         printList(head);     } } 
Python
# Python3 program to remove duplicate # nodes from a sorted linked list class Node:     def __init__(self, x):         self.data = x         self.next = None   def remove_duplicates(head):     curr = head      # Traverse the list     while curr and curr.next:                # Check if next value is the same as curr         if curr.data == curr.next.data:             next_next = curr.next.next             curr.next = next_next         else:             curr = curr.next      return head   def print_list(node):     while node:         print(node.data, end=" ")         node = node.next     print()   if __name__ == "__main__":        # Create a sorted linked list:     # 11->11->11->13->13->20     head = Node(11)     head.next = Node(11)     head.next.next = Node(11)     head.next.next.next = Node(13)     head.next.next.next.next = Node(13)     head.next.next.next.next.next = Node(20)      print("Linked list before duplicate removal:")     print_list(head)      head = remove_duplicates(head)      print("Linked list after duplicate removal:")     print_list(head) 
C#
// C# program to remove duplicates // from a sorted linked list using System;  public class Node {    public  int data;    public  Node next;    public  Node(int x) {         data = x;         next = null;     } }  class GfG {        // Function to remove duplicates     static Node RemoveDuplicates(Node head) {         Node curr = head;          // Traverse the list         while (curr != null && curr.next != null) {                        // Check if next value is the same as curr             if (curr.data == curr.next.data) {                 Node nextNext = curr.next.next;                 curr.next = nextNext;             }             else {                 curr = curr.next;             }         }         return head;     }      static void PrintList(Node node) {         while (node != null) {             Console.Write(node.data + " ");             node = node.next;         }         Console.WriteLine();     }      static void Main() {                // Create a sorted linked list:         // 11->11->11->13->13->20         Node head = new Node(11);         head.next = new Node(11);         head.next.next = new Node(11);         head.next.next.next = new Node(13);         head.next.next.next.next = new Node(13);         head.next.next.next.next.next = new Node(20);          Console.WriteLine(             "Linked list before duplicate removal:");         PrintList(head);          head = RemoveDuplicates(head);          Console.WriteLine(             "Linked list after duplicate removal:");         PrintList(head);     } } 
JavaScript
// JavaScript program to remove duplicates // from a sorted linked list  class Node {     constructor(x) {         this.data = x;         this.next = null;     } }  function removeDuplicates(head) {     let curr = head;      // Traverse the list     while (curr && curr.next) {              // Check if next value is the same as curr         if (curr.data === curr.next.data) {             let nextNext = curr.next.next;             curr.next = nextNext;         }         else {             curr = curr.next;         }     }      return head; }  function printList(node) {     let current = node;     while (current) {         process.stdout.write(current.data + " ");         current = current.next;     }     console.log(); }  // Create a sorted linked list: // 11->11->11->13->13->20 let head = new Node(11); head.next = new Node(11); head.next.next = new Node(11); head.next.next.next = new Node(13); head.next.next.next.next = new Node(13); head.next.next.next.next.next = new Node(20);  console.log("Linked list before duplicate removal:"); printList(head);  head = removeDuplicates(head);  console.log("Linked list after duplicate removal:"); printList(head); 

Output
Linked list before duplicate removal: 11 11 11 13 13 20  Linked list after duplicate removal: 11 13 20  

Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1)

[Alternate Approach] Using Recursion – O(n) Time and O(n) Space:

The idea is similar to the iterative approach. Here we are using the recursion to check each node and its next for duplicates. Please note that the iterative approach would be better in terns of time and space. The recursive approach can be good fun exercise or a question in an interview / exam.

Follow the steps below to solve the problem:

  • If the curr node or its next node is NULL, return the curr node.
  • If the current node’s data equals the next node’s data, adjust pointers to skip the duplicate.
  • If no duplicate, recursively process the next node.

Below is the implementation of the above approach: 

C++
// C++ Program to remove duplicates from a // sorted linked list  #include <iostream> using namespace std;  class Node {   public:     int data;     Node *next;      Node(int new_data) {         data = new_data;         next = nullptr;     } };  // Function to remove duplicates void removeDuplicates(Node *head) {        // Base case: if the list is empty, return     if (head == NULL)         return;        // Check if the next node exists     if (head->next != NULL) {                // If current node has duplicate         // data with the next node         if (head->data == head->next->data) {             head->next = head->next->next;             removeDuplicates(head);         }         else{             removeDuplicates(head->next);         }     } }  void printList(Node *node) {     while (node != NULL) {         cout << node->data << " ";         node = node->next;     }     cout << endl; }  int main() {        // Create a sorted linked list     // 11->11->11->13->13->20     Node *head = new Node(11);     head->next = new Node(11);     head->next->next = new Node(11);     head->next->next->next = new Node(13);     head->next->next->next->next = new Node(13);     head->next->next->next->next->next = new Node(20);      cout << "Linked list before duplicate removal:" << endl;     printList(head);      removeDuplicates(head);      cout << "Linked list after duplicate removal:" << endl;     printList(head);      return 0; } 
C
// C Program to remove duplicates from a // sorted linked list #include <stdio.h>  struct Node {     int data;     struct Node *next; };  struct Node *createNode(int new_data) {     struct Node *new_node =        (struct Node *)malloc(sizeof(struct Node));     new_node->data = new_data;     new_node->next = NULL;     return new_node; }  // Function to remove duplicates void removeDuplicates(struct Node *head) {        // Base case: if the list is empty, return     if (head == NULL)         return;        // Check if the next node exists     if (head->next != NULL) {                // If current node has duplicate data         // with the next node         if (head->data == head->next->data) {             head->next = head->next->next;             removeDuplicates(head);         }         else             removeDuplicates(head->next);     } }  void printList(struct Node *node) {     while (node != NULL) {         printf("%d ", node->data);         node = node->next;     }     printf("\n"); }  int main() {        // Create a sorted linked list:     // 11->11->11->13->13->20     struct Node *head = createNode(11);     head->next = createNode(11);     head->next->next = createNode(11);     head->next->next->next = createNode(13);     head->next->next->next->next = createNode(13);     head->next->next->next->next->next = createNode(20);      printf("Linked list before duplicate removal:\n");     printList(head);      removeDuplicates(head);      printf("Linked list after duplicate removal:\n");     printList(head);      return 0; } 
Java
// Java program to remove duplicates // from a sorted linked list import java.io.*;  class Node {     int data;     Node next;     Node(int x) {         data = x;         next = null;     } }  class GfG {      // Function to remove duplicates      static void removeDuplicates(Node head) {                // Base case: if the list is empty, return         if (head == null)             return;          // Check if the next node exists         if (head.next != null) {              // If current node has duplicate data with the             // next node             if (head.data == head.next.data) {                 head.next = head.next.next;                 removeDuplicates(head);             }             else {                 // Continue with next node                 removeDuplicates(head.next);             }         }     }      static void printList(Node node) {         while (node != null) {             System.out.print(node.data + " ");             node = node.next;         }         System.out.println();     }      public static void main(String[] args) {                // Create a sorted linked list:         // 11->11->11->13->13->20         Node head = new Node(11);         head.next = new Node(11);         head.next.next = new Node(11);         head.next.next.next = new Node(13);         head.next.next.next.next = new Node(13);         head.next.next.next.next.next = new Node(20);          System.out.println(             "Linked list before duplicate removal:");         printList(head);          removeDuplicates(head);          System.out.println(             "Linked list after duplicate removal:");         printList(head);     } } 
Python
# Python3 program to remove duplicate # nodes from a sorted linked list  class Node:     def __init__(self, x):         self.data = x         self.next = None   def remove_duplicates(head):      # Base case: if the list is empty, return     if head is None:         return      # Check if the next node exists     if head.next is not None:                # If current node has duplicate data with the next node         if head.data == head.next.data:             head.next = head.next.next             remove_duplicates(head)         else:               # Continue with next node             remove_duplicates(head.next)   def print_list(node):     while node:         print(node.data, end=" ")         node = node.next     print()   if __name__ == "__main__":      # Create a sorted linked list:     # 11->11->11->13->13->20     head = Node(11)     head.next = Node(11)     head.next.next = Node(11)     head.next.next.next = Node(13)     head.next.next.next.next = Node(13)     head.next.next.next.next.next = Node(20)      print("Linked list before duplicate removal:")     print_list(head)      remove_duplicates(head)      print("Linked list after duplicate removal:")     print_list(head) 
C#
// C# program to remove duplicates from a sorted linked list using System;  public class Node {     public int data;     public Node next;     public Node(int x) {         data = x;         next = null;     } }  class GfG {      // Function to remove duplicates     static void RemoveDuplicates(Node head) {          // Base case: if the list is empty, return         if (head == null)             return;                // Check if the next node exists         if (head.next != null) {                        // If current node has duplicate data with             // the next node             if (head.data == head.next.data) {                 head.next = head.next.next;                 RemoveDuplicates(head);             }             else {                                // Continue with next node                 RemoveDuplicates(head.next);             }         }     }      static void PrintList(Node node) {         while (node != null) {             Console.Write(node.data + " ");             node = node.next;         }         Console.WriteLine();     }      static void Main() {                // Create a sorted linked list:         // 11->11->11->13->13->20         Node head = new Node(11);         head.next = new Node(11);         head.next.next = new Node(11);         head.next.next.next = new Node(13);         head.next.next.next.next = new Node(13);         head.next.next.next.next.next = new Node(20);          Console.WriteLine(             "Linked list before duplicate removal:");         PrintList(head);          RemoveDuplicates(head);          Console.WriteLine(             "Linked list after duplicate removal:");         PrintList(head);     } } 
JavaScript
// JavaScript program to remove duplicates from a sorted // linked list  class Node {     constructor(x) {         this.data = x;         this.next = null;     } }  function removeDuplicates(head) {      // Base case: if the list is empty, return     if (head === null)         return;              // Check if the next node exists     if (head.next !== null) {              // If current node has duplicate data         // with the next node         if (head.data === head.next.data) {             head.next = head.next.next;             removeDuplicates(head);         }         else {             // Continue with next node             removeDuplicates(head.next);         }     } }  function printList(node) {     let current = node;     while (current) {         process.stdout.write(current.data + " ");         current = current.next;     }     console.log(); }  // Create a sorted linked list: //	11->11->11->13->13->20 let head = new Node(11); head.next = new Node(11); head.next.next = new Node(11); head.next.next.next = new Node(13); head.next.next.next.next = new Node(13); head.next.next.next.next.next = new Node(20);  console.log("Linked list before duplicate removal:"); printList(head);  removeDuplicates(head);  console.log("Linked list after duplicate removal:"); printList(head); 

Output
Linked list before duplicate removal: 11 11 11 13 13 20  Linked list after duplicate removal: 11 13 20  

Time Complexity: O(n) , where n is the number of nodes in the given linked list.
Auxiliary Space: O(n)



Next Article
Remove duplicates from an unsorted doubly linked list
author
kartik
Improve
Article Tags :
  • DSA
  • Linked List
  • Adobe
  • Myntra
  • Oracle
  • Visa
Practice Tags :
  • Adobe
  • Myntra
  • Oracle
  • Visa
  • Linked List

Similar Reads

  • 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
  • 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 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 : empt
    10 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
  • Merge two sorted linked list without duplicates
    Merge two sorted linked list of size n1 and n2. The duplicates in two linked list should be present only once in the final sorted linked list. Examples: Input : list1: 1->1->4->5->7 list2: 2->4->7->9Output : 1 2 4 5 7 9Source: Microsoft on Campus Placement and Interview Question
    15+ min read
  • Merge Sort for Doubly Linked List
    Given a doubly linked list, The task is to sort the doubly linked list in non-decreasing order using merge sort.Examples: Input: 10 <-> 8 <-> 4 <-> 2Output: 2 <-> 4 <-> 8 <-> 10Input: 5 <-> 3 <-> 2Output: 2 <-> 3 <-> 5 Note: Merge sort for
    13 min read
  • Delete adjacent duplicate nodes from the Doubly Linked List
    Given a doubly linked list. The problem is to remove all adjacent duplicate nodes from the list such that the final modified doubly linked list does not contain any adjacent duplicate nodes. Examples: Approach: The approach uses stack to keep track of the adjacent nodes at any point in the modified
    11 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