# Remove duplicates from a sorted linked list

Last Updated : 02 Apr, 2024

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

Algorithm: Traverse the list from the head (or start) node. While traversing, compare each node with its next node. If the data of the next node is the same as the current node then delete the next node. Before we delete a node, we need to store the next pointer of the node

Implementation: Functions other than removeDuplicates() are just to create a linked list and test removeDuplicates().

C++ ```/* C++ Program to remove duplicates from a sorted linked * list */ #include <bits/stdc++.h> using namespace std; /* Link list node */ class Node { public: int data; Node* next; Node(int x) { data = x; next = NULL; } }; /* The function removes duplicates from a sorted list */ void removeDuplicates(Node* head) { /* Pointer to traverse the linked list */ Node* current = head; /* Pointer to store the next pointer of a node to be * deleted*/ Node* next_next; /* do nothing if the list is empty */ if (current == NULL) return; /* Traverse the list till last node */ while (current->next != NULL) { /* Compare current node with next node */ if (current->data == current->next->data) { /* The sequence of steps is important*/ next_next = current->next->next; free(current->next); current->next = next_next; } else /* This is tricky: only advance if no deletion */ { current = current->next; } } } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked * list */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(new_data); /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { cout << " " << node->data; node = node->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); cout << "Linked list before duplicate removal " << endl; printList(head); /* Remove duplicates from linked list */ removeDuplicates(head); cout << "\nLinked list after duplicate removal " << endl; printList(head); return 0; } // This code is contributed by rathbhupendra ``` C ```/* C Program to remove duplicates from a sorted linked list */ #include <stdio.h> #include <stdlib.h> /* Link list node */ struct Node { int data; struct Node* next; }; /* The function removes duplicates from a sorted list */ void removeDuplicates(struct Node* head) { /* Pointer to traverse the linked list */ struct Node* current = head; /* Pointer to store the next pointer of a node to be * deleted*/ struct Node* next_next; /* do nothing if the list is empty */ if (current == NULL) return; /* Traverse the list till last node */ while (current->next != NULL) { /* Compare current node with next node */ if (current->data == current->next->data) { /* The sequence of steps is important*/ next_next = current->next->next; free(current->next); current->next = next_next; } else /* This is tricky: only advance if no deletion */ { current = current->next; } } } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked * list */ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(struct Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } } /* Driver program to test above functions*/ int main() { /* Start with the empty list */ struct Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); printf("\n Linked list before duplicate removal \n"); printList(head); /* Remove duplicates from linked list */ removeDuplicates(head); printf("\n 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 LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } void removeDuplicates() { /*Another reference to head*/ Node curr = head; /* Traverse list till the last node */ while (curr != null) { Node temp = curr; /*Compare current node with the next node and keep on deleting them until it matches the current node data */ while (temp != null && temp.data == curr.data) { temp = temp.next; } /*Set current node next to the next different element denoted by temp*/ curr.next = temp; curr = curr.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); System.out.println( "List before removal of duplicates"); llist.printList(); llist.removeDuplicates(); System.out.println( "List after removal of elements"); llist.printList(); } } /* This code is contributed by Rajat Mishra */ ``` C# ```// C# program to remove duplicates // from a sorted linked list using System; public class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } void removeDuplicates() { /*Another reference to head*/ Node current = head; /* Pointer to store the next pointer of a node to be deleted*/ Node next_next; /* do nothing if the list is empty */ if (head == null) return; /* Traverse list till the last node */ while (current.next != null) { /*Compare current node with the next node */ if (current.data == current.next.data) { next_next = current.next.next; current.next = null; current.next = next_next; } else // advance if no deletion current = current.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); Console.WriteLine( "List before removal of duplicates"); llist.printList(); llist.removeDuplicates(); Console.WriteLine("List after removal of elements"); llist.printList(); } } /* This code is contributed by 29AjayKumar */ ``` Javascript ```<script> // Javascript program to remove duplicates from a sorted linked list /* Linked list Node*/ class Node { constructor(d) { this.data = d; this.next = null; } } let head=new Node(); // head of list function removeDuplicates() { /*Another reference to head*/ let curr = head; /* Traverse list till the last node */ while (curr != null) { let temp = curr; /*Compare current node with the next node and keep on deleting them until it matches the current node data */ while(temp!=null && temp.data==curr.data) { temp = temp.next; } /*Set current node next to the next different element denoted by temp*/ curr.next = temp; curr = curr.next; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { let temp = head; while (temp != null && temp.data) { document.write(temp.data+" "); temp = temp.next; } document.write("<br>"); } /* Driver program to test above functions */ push(20) push(13) push(13) push(11) push(11) push(11) document.write("List before removal of duplicates "); printList(); removeDuplicates(); document.write("List after removal of elements "); printList(); // This code is contributed by unknown2108 </script> ``` Python3 ```# Python3 program to remove duplicate # nodes from a sorted linked list # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node # at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Given a reference to the head of a # list and a key, delete the first # occurrence of key in linked list def deleteNode(self, key): # Store head node temp = self.head # If head node itself holds the # key to be deleted if (temp is not None): if (temp.data == key): self.head = temp.next temp = None return # Search for the key to be deleted, # keep track of the previous node as # we need to change 'prev.next' while(temp is not None): if temp.data == key: break prev = temp temp = temp.next # if key was not present in # linked list if(temp == None): return # Unlink the node from linked list prev.next = temp.next temp = None # Utility function to print the # linked LinkedList def printList(self): temp = self.head while(temp): print(temp.data, end=' ') temp = temp.next # This function removes duplicates # from a sorted list def removeDuplicates(self): temp = self.head if temp is None: return while temp.next is not None: if temp.data == temp.next.data: new = temp.next.next temp.next = None temp.next = new else: temp = temp.next return self.head # Driver Code llist = LinkedList() llist.push(20) llist.push(13) llist.push(13) llist.push(11) llist.push(11) llist.push(11) print("Created Linked List: ") llist.printList() print() print("Linked List after removing", "duplicate elements:") llist.removeDuplicates() llist.printList() # This code is contributed by # Dushyant Pathak. ```

Output
```Linked list before duplicate removal
11 11 11 13 13 20
11 13 20```

Time Complexity: O(n) where n is the number of nodes in the given linked list.
Auxiliary Space: O(1) , as there is no extra space used.

Recursive Approach :

C++ ```/* C++ Program to remove duplicates from a sorted linked list */ #include <bits/stdc++.h> using namespace std; /* Link list node */ class Node { public: int data; Node* next; Node(int x) { data = x; next = NULL; } }; /* The function removes duplicates from a sorted list */ void removeDuplicates(Node* head) { /* Pointer to store the pointer of a node to be * deleted*/ Node* to_free; /* do nothing if the list is empty */ if (head == NULL) return; /* Traverse the list till last node */ if (head->next != NULL) { /* Compare head node with next node */ if (head->data == head->next->data) { /* The sequence of steps is important. to_free pointer stores the next of head pointer which is to be deleted.*/ to_free = head->next; head->next = head->next->next; free(to_free); removeDuplicates(head); } else /* This is tricky: only advance if no deletion */ { removeDuplicates(head->next); } } } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked list */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(new_data); /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { cout << " " << node->data; node = node->next; } } /* Driver code*/ int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); cout << "Linked list before duplicate removal "; printList(head); /* Remove duplicates from linked list */ removeDuplicates(head); cout << "\nLinked list after duplicate removal "; printList(head); return 0; } // This code is contributed by Ashita Gupta ``` Java ```// Java Program to remove duplicates // from a sorted linked list import java.io.*; class GFG { /* Link list node */ static class Node { int data; Node next; Node(int x) { data = x; next = null; } }; // The function removes duplicates // from a sorted list static Node removeDuplicates(Node head) { /* Pointer to store the pointer of a node to be deleted*/ Node to_free; /* do nothing if the list is empty */ if (head == null) return null; /* Traverse the list till last node */ if (head.next != null) { /* Compare head node with next node */ if (head.data == head.next.data) { /* The sequence of steps is important. to_free pointer stores the next of head pointer which is to be deleted.*/ to_free = head.next; head.next = head.next.next; removeDuplicates(head); } /* This is tricky: only advance if no deletion */ else { removeDuplicates(head.next); } } return head; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked list */ static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* link the old list of the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { System.out.print(" " + node.data); node = node.next; } } /* Driver code*/ public static void main(String args[]) { /* Start with the empty list */ Node head = null; /* Let us create a sorted linked list to test the functions Created linked list will be 11.11.11.13.13.20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); System.out.println("Linked list before" + " duplicate removal "); printList(head); /* Remove duplicates from linked list */ head = removeDuplicates(head); System.out.println("\nLinked list after" + " duplicate removal "); printList(head); } } // This code is contributed by Arnab Kundu ``` Javascript ```<script> // JavaScript Program to remove duplicates // from a sorted linked list /* Link list node */ class Node { constructor(val) { this.data = val; this.next = null; } } // The function removes duplicates // from a sorted list function removeDuplicates(head) { /* Pointer to store the pointer of a node to be deleted */ var to_free; /* do nothing if the list is empty */ if (head == null) return null; /* Traverse the list till last node */ if (head.next != null) { /* Compare head node with next node */ if (head.data == head.next.data) { /* The sequence of steps is important. to_free pointer stores the next of head pointer which is to be deleted. */ to_free = head.next; head.next = head.next.next; removeDuplicates(head); } /* This is tricky: only advance if no deletion */ else { removeDuplicates(head.next); } } return head; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the linked list */ function push(head_ref , new_data) { /* allocate node */ var new_node = new Node(new_data); /* link the old list of the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ (head_ref) = new_node; return head_ref; } /* Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write(" " + node.data); node = node.next; } } /* Driver code */ /* Start with the empty list */ var head = null; /* Let us create a sorted linked list to test the functions Created linked list will be 11.11.11.13.13.20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); document.write("Linked list before" + " duplicate removal <br/>"); printList(head); /* Remove duplicates from linked list */ head = removeDuplicates(head); document.write("<br/>Linked list after" + " duplicate removal <br/>"); printList(head); // This code is contributed by todaysgaurav </script> ``` Python3 ```# Python3 Program to remove duplicates # from a sorted linked list import math # Link list node class Node: def __init__(self, data): self.data = data self.next = None # The function removes duplicates # from a sorted list def removeDuplicates(head): # Pointer to store the pointer of a node # to be deleted to_free # do nothing if the list is empty if (head == None): return # Traverse the list till last node if (head.next != None): # Compare head node with next node if (head.data == head.next.data): # The sequence of steps is important. # to_free pointer stores the next of head # pointer which is to be deleted. to_free = head.next head.next = head.next.next # free(to_free) removeDuplicates(head) # This is tricky: only advance if no deletion else: removeDuplicates(head.next) return head # UTILITY FUNCTIONS # Function to insert a node at the # beginning of the linked list def push(head_ref, new_data): # allocate node new_node = Node(new_data) # link the old list of the new node new_node.next = head_ref # move the head to point to the new node head_ref = new_node return head_ref # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end=" ") node = node.next # Driver code if __name__ == '__main__': # Start with the empty list head = None # Let us create a sorted linked list # to test the functions # Created linked list will be 11.11.11.13.13.20 head = push(head, 20) head = push(head, 13) head = push(head, 13) head = push(head, 11) head = push(head, 11) head = push(head, 11) print("Linked list before duplicate removal ", end="") printList(head) # Remove duplicates from linked list removeDuplicates(head) print("\nLinked list after duplicate removal ", end="") printList(head) # This code is contributed by Srathore ```

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)

Another Approach: Create a pointer that will point towards the first occurrence of every element and another pointer temp which will iterate to every element and when the value of the previous pointer is not equal to the temp pointer, we will set the pointer of the previous pointer to the first occurrence of another node.

Below is the implementation of the above approach:

C ```// C program to remove duplicates from a sorted linked list #include <stdio.h> #include <stdlib.h> /* Link list node */ typedef struct Node { int data; struct Node* next; } Node; // Function to remove duplicates // from the given linked list Node* removeDuplicates(Node* head) { // Two references to head temp will iterate to the whole // Linked List prev will point towards the first // occurrence of every element Node *temp = head, *prev = head; // Traverse list till the last node while (temp != NULL) { // Compare values of both pointers if (temp->data != prev->data) { // if the value of prev is not equal to the // value of temp that means there are no more // occurrences of the prev data-> So we can set // the next of prev to the temp node->*/ prev->next = temp; prev = temp; } // Set the temp to the next node temp = temp->next; } // This is the edge case if there are more than one // occurrences of the last element if (prev != temp) prev->next = NULL; return head; } void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = (Node*)malloc(sizeof(Node)); /* put in the data */ new_node->data = new_data; /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print linked list */ void printList(Node* head) { Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } /* Driver code */ int main() { Node* llist = NULL; push(&llist, 20); push(&llist, 13); push(&llist, 13); push(&llist, 11); push(&llist, 11); push(&llist, 11); printf("List before removal of duplicates\n"); printList(llist); printf("List after removal of elements\n"); llist = removeDuplicates(llist); printList(llist); } // This code is contributed by Sania Kumari Gupta ``` Java ```// Java program to remove duplicates // from a sorted linked list import java.io.*; class LinkedList { // head of list Node head; // Linked list Node class Node { int data; Node next; Node(int d) { data = d; next = null; } } // Function to remove duplicates from the given linked // list void removeDuplicates() { // Two references to head temp will iterate to the // whole Linked List prev will point towards the // first occurrence of every element Node temp = head, prev = head; // Traverse list till the last node while (temp != null) { // Compare values of both pointers if (temp.data != prev.data) { // if the value of prev is not equal to the // value of temp that means there are no // more occurrences of the prev data. So we // can set the next of prev to the temp // node. prev.next = temp; prev = temp; } // Set the temp to the next node temp = temp.next; } // This is the edge case if there are more than one // occurrences of the last element if (prev != temp) prev.next = null; } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); System.out.print("List before "); System.out.println("removal of duplicates"); llist.printList(); llist.removeDuplicates(); System.out.println( "List after removal of elements"); llist.printList(); } } // This code is contributed by Sania Kumari Gupta ``` C# ```// C# program to remove duplicates // from a sorted linked list using System; class LinkedList { // head of list public Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Function to remove duplicates // from the given linked list void removeDuplicates() { // Two references to head // temp will iterate to the // whole Linked List // prev will point towards // the first occurrence of every element Node temp = head, prev = head; // Traverse list till the last node while (temp != null) { // Compare values of both pointers if (temp.data != prev.data) { /* if the value of prev is not equal to the value of temp that means there are no more occurrences of the prev data. So we can set the next of prev to the temp node.*/ prev.next = temp; prev = temp; } /*Set the temp to the next node*/ temp = temp.next; } /*This is the edge case if there are more than one occurrences of the last element*/ if (prev != temp) { prev.next = null; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Driver code */ public static void Main(string[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(13); llist.push(13); llist.push(11); llist.push(11); llist.push(11); Console.Write("List before "); Console.WriteLine("removal of duplicates"); llist.printList(); llist.removeDuplicates(); Console.WriteLine("List after removal of elements"); llist.printList(); } } // This code is contributed by rutvik_56 ``` Javascript ```<script> // javascript program to remove duplicates // from a sorted linked list // head of list var head; // Linked list Node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to remove duplicates // from the given linked list function removeDuplicates() { // Two references to head // temp will iterate to the // whole Linked List // prev will point towards // the first occurrence of every element var temp = head, prev = head; // Traverse list till the last node while (temp != null) { // Compare values of both pointers if (temp.data != prev.data) { /* * if the value of prev is not equal to the value of temp that means there are * no more occurrences of the prev data. So we can set the next of prev to the * temp node. */ prev.next = temp; prev = temp; } /* Set the temp to the next node */ temp = temp.next; } /* * This is the edge case if there are more than one occurrences of the last * element */ if (prev != temp) { prev.next = null; } } /* Utility functions */ /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Function to print linked list */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ push(20); push(13); push(13); push(11); push(11); push(11); document.write("List before "); document.write("removal of duplicates<br/>"); printList(); removeDuplicates(); document.write("List after removal of elements<br/>"); printList(); // This code contributed by aashish1995 </script> ``` C++14 ```// C++ program to remove duplicates // from a sorted linked list #include <bits/stdc++.h> using namespace std; // Linked list Node struct Node { int data; Node* next; Node(int d) { data = d; next = NULL; } }; // Function to remove duplicates // from the given linked list Node* removeDuplicates(Node* head) { // Two references to head temp will iterate to the whole // Linked List prev will point towards the first // occurrence of every element Node *temp = head, *prev = head; // Traverse list till the last node while (temp != NULL) { // Compare values of both pointers if (temp->data != prev->data) { // if the value of prev is not equal to the // value of temp that means there are no more // occurrences of the prev data-> So we can set // the next of prev to the temp node->*/ prev->next = temp; prev = temp; } // Set the temp to the next node temp = temp->next; } // This is the edge case if there are more than one // occurrences of the last element if (prev != temp) prev->next = NULL; return head; } Node* push(Node* head, int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node* new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node->next = head; /* 4. Move the head to point to new Node */ head = new_node; return head; } /* Function to print linked list */ void printList(Node* head) { Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } /* Driver code */ int main() { Node* llist = NULL; llist = push(llist, 20); llist = push(llist, 13); llist = push(llist, 13); llist = push(llist, 11); llist = push(llist, 11); llist = push(llist, 11); cout << ("List before removal of duplicates\n"); printList(llist); cout << ("List after removal of elements\n"); llist = removeDuplicates(llist); printList(llist); } // This code is contributed by Sania Kumari Gupta ``` Python3 ```# Python3 program to remove duplicates # from a sorted linked list import math # Link list node class Node: def __init__(self, data): self.data = data self.next = None # The function removes duplicates # from the given linked list def removeDuplicates(head): # Do nothing if the list consist of # only one element or empty if (head == None and head.next == None): return # Construct a pointer # pointing towards head current = head # Initialise a while loop till the # second last node of the linkedlist while (current.next): # If the data of current and next # node is equal we will skip the # node between them if current.data == current.next.data: current.next = current.next.next # If the data of current and # next node is different move # the pointer to the next node else: current = current.next return # UTILITY FUNCTIONS # Function to insert a node at the # beginning of the linked list def push(head_ref, new_data): # Allocate node new_node = Node(new_data) # Put in the data new_node.data = new_data # Link the old list of # the new node new_node.next = head_ref # Move the head to point # to the new node head_ref = new_node return head_ref # Function to print nodes # in a given linked list def printList(node): while (node != None): print(node.data, end=" ") node = node.next # Driver code if __name__ == '__main__': head = None head = push(head, 20) head = push(head, 13) head = push(head, 13) head = push(head, 11) head = push(head, 11) head = push(head, 11) print("List before removal of " "duplicates ", end="") printList(head) removeDuplicates(head) print("\nList after removal of " "elements ", end="") printList(head) # This code is contributed by MukulTomar ```

Output
```List before removal of duplicates
11 11 11 13 13 20
List after removal of elements
11 13 20 ```

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

Another Approach: Using Maps

The idea is to push all the values in a map and printing its keys.

Below is the implementation of the above approach:

C++ ```// CPP program for the above approach #include <bits/stdc++.h> using namespace std; /* Link list node */ struct Node { int data; Node* next; Node(int x) { data = x; next = NULL; } }; /* Function to insert a node at the beginning of the linked * list */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(new_data); /* link the old list of the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << " "; node = node->next; } } // Function to remove duplicates void removeDuplicates(Node* head) { unordered_map<int, bool> track; Node* temp = head; while (temp) { if (track.find(temp->data) == track.end()) { cout << temp->data << " "; } track[temp->data] = true; temp = temp->next; } } // Driver Code int main() { Node* head = NULL; /* Created linked list will be 11->11->11->13->13->20 */ push(&head, 20); push(&head, 13); push(&head, 13); push(&head, 11); push(&head, 11); push(&head, 11); cout << "Linked list before duplicate removal "; printList(head); cout << "\nLinked list after duplicate removal "; removeDuplicates(head); return 0; } // This code is contributed by yashbeersingh42 ``` Java ```// Java program for the above approach import java.io.*; import java.util.*; class Node { int data; Node next; Node(int x) { data = x; next = null; } } class GFG { /* Function to insert a node at the beginning of the linked * list */ static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* link the old list of the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ head_ref = new_node; return head_ref; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Function to remove duplicates static void removeDuplicates(Node head) { HashMap<Integer, Boolean> track = new HashMap<>(); Node temp = head; while (temp != null) { if (!track.containsKey(temp.data)) { System.out.print(temp.data + " "); } track.put(temp.data, true); temp = temp.next; } } // Driver Code public static void main(String[] args) { Node head = null; /* Created linked list will be 11->11->11->13->13->20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); System.out.print( "Linked list before duplicate removal "); printList(head); System.out.print( "\nLinked list after duplicate removal "); removeDuplicates(head); } } ``` C# ```// C# program for the above approach using System; using System.Collections.Generic; public class Node { public int data; public Node next; public Node(int x) { data = x; next = null; } } public class GFG { /* Function to insert a node at the beginning of the linked * list */ static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* link the old list of the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ head_ref = new_node; return head_ref; } /* Function to print nodes in a given linked list */ static void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Function to remove duplicates static void removeDuplicates(Node head) { Dictionary<int, bool> track = new Dictionary<int, bool>(); Node temp = head; while (temp != null) { if (!track.ContainsKey(temp.data)) { Console.Write(temp.data + " "); track.Add(temp.data, true); } temp = temp.next; } } // Driver Code static public void Main() { Node head = null; /* Created linked list will be 11->11->11->13->13->20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); Console.Write( "Linked list before duplicate removal "); printList(head); Console.Write( "\nLinked list after duplicate removal "); removeDuplicates(head); } } // This code is contributed by rag2127 ``` Javascript ```<script> // Javascript program for the above approach class Node { constructor(x) { this.data = x; this.next = null; } } /* Function to insert a node at the beginning of the linked * list */ function push(head_ref, new_data) { /* allocate node */ let new_node = new Node(new_data); /* link the old list of the new node */ new_node.next = (head_ref); /* move the head to point to the new node */ head_ref = new_node; return head_ref; } /* Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Function to remove duplicates function removeDuplicates(head) { let track = new Map(); let temp = head; while(temp != null) { if (!track.has(temp.data)) { document.write(temp.data + " "); } track.set(temp.data, true); temp = temp.next; } } // Driver Code let head = null; /* Created linked list will be 11->11->11->13->13->20 */ head = push(head, 20); head = push(head, 13); head = push(head, 13); head = push(head, 11); head = push(head, 11); head = push(head, 11); document.write("Linked list before duplicate removal "); printList(head); document.write("<br>Linked list after duplicate removal "); removeDuplicates(head); // This code is contributed by patel2127 </script> ``` Python3 ```# Python program for the above approach class Node: def __init__(self, x): self.data = x self.next = None # Function to insert a node at # the beginning of the linked list def push(head_ref, new_data): # allocate node new_node = Node(new_data) # link the old list of the new node new_node.next = (head_ref) # move the head to point to the new node head_ref = new_node return head_ref # Function to print nodes in a given linked list def printList(node): while (node != None): print(node.data, end=" ") node = node.next # Function to remove duplicates def removeDuplicates(head): track = {} temp = head while(temp != None): if (not temp.data in track): print(temp.data, end=" ") track[temp.data] = True temp = temp.next # Driver Code head = None # Created linked list will be 11->11->11->13->13->20 head = push(head, 20) head = push(head, 13) head = push(head, 13) head = push(head, 11) head = push(head, 11) head = push(head, 11) print("Linked list before duplicate removal ", end=" ") printList(head) print("\nLinked list after duplicate removal ", end=" ") removeDuplicates(head) # This code is contributed by _Saurabh_jaiswal ```

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)

Using Set data structure:

We know that set data structure always stores the unique element.

so, the intuition comes from there-

Explanation:

The code then defines a class Solution which contains the deleteDuplicates function. The function takes a pointer to the head of the linked list as an argument. If the head is empty, it returns it. Otherwise, it initializes a set data structure to store unique values in the linked list. It also declares two pointers curr and prev to traverse the linked list and keep track of the previous node, respectively.

The code then enters a while loop that continues as long as curr is not NULL. In each iteration, it checks if the value of the current node already exists in the set. If it does, the code updates the next pointer of the previous node to skip the current node and remove it from the linked list. If the value does not exist in the set, it is inserted into the set and prev is updated to become the current node. After each iteration, curr is updated to point to the next node.

The main function demonstrates how to use the deleteDuplicates function by creating a linked list with values 1, 2, 2,2, 3 ,3,3and calling the function to remove duplicates. It then prints the linked list after duplicates are removed.

Note: The code assumes that the linked list is sorted and the duplicates appear consecutively

Below is the implementation for above approach :

C++ ```#include <iostream> #include <set> using namespace std; // Define a node in a linked list struct ListNode { int val; // Value of the node // Pointer to the next node in the linked list ListNode* next; ListNode(int x) { this->val = x; this->next = NULL; } }; class Solution { public: // Remove duplicates from sorted linked list using set ListNode* deleteDuplicates(ListNode* head) { // Return head if it's empty if (!head) return head; // Use set to store unique values in linked list set<int> set; ListNode* curr = head; // Pointer to traverse the linked list ListNode* prev = NULL; // Pointer to keep track of // the previous node // Iterate through the linked list while (curr) { // If the current value already exists in set, // remove the node if (set.count(curr->val)) { prev->next = curr->next; } else { // Otherwise, add the value to set and move // on to the next node set.insert(curr->val); prev = curr; } curr = curr->next; } // Return the head of the linked list return head; } }; int main() { // Initialize linked list with values 1, 2, 2, 3 ListNode* head = new ListNode(1); head->next = new ListNode(2); head->next->next = new ListNode(2); head->next->next->next = new ListNode(2); head->next->next->next->next = new ListNode(3); head->next->next->next->next->next = new ListNode(3); head->next->next->next->next->next->next = new ListNode(3); ListNode* BeforePrinter = head; cout << "Before removing duplicates linked list is:" << endl; while (BeforePrinter) { cout << BeforePrinter->val << " "; BeforePrinter = BeforePrinter->next; } std::cout << std::endl; Solution solution; // Remove duplicates from the linked list using the // deleteDuplicates function head = solution.deleteDuplicates(head); // Print the linked list after removing duplicates cout << "after removing duplicates linked list is:" << endl; ListNode* curr = head; while (curr) { cout << curr->val << " "; curr = curr->next; } cout << endl; return 0; } // This code is contributed by Veerendra Singh Rajpoot ``` Java ```import java.util.*; class ListNode { int val; // Value of the node ListNode next; // Pointer to the next node in the linked list ListNode(int x) { this.val = x; this.next = null; } } class Solution { // Remove duplicates from sorted linked list using set public ListNode deleteDuplicates(ListNode head) { // Return head if it's empty if (head == null) return head; // Use set to store unique values in linked list Set<Integer> set = new HashSet<>(); ListNode curr = head; // Pointer to traverse the linked list ListNode prev = null; // Pointer to keep track of // the previous node // Iterate through the linked list while (curr != null) { // If the current value already exists in set, // remove the node if (set.contains(curr.val)) { prev.next = curr.next; } else { // Otherwise, add the value to set and move // on to the next node set.add(curr.val); prev = curr; } curr = curr.next; } // Return the head of the linked list return head; } } public class Main { public static void main(String[] args) { // Initialize linked list with values 1, 2, 2, 3 ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(2); head.next.next.next = new ListNode(2); head.next.next.next.next = new ListNode(3); head.next.next.next.next.next = new ListNode(3); head.next.next.next.next.next.next = new ListNode(3); ListNode BeforePrinter = head; System.out.println( "Before removing duplicates linked list is:"); while (BeforePrinter != null) { System.out.print(BeforePrinter.val + " "); BeforePrinter = BeforePrinter.next; } System.out.println(); Solution solution = new Solution(); // Remove duplicates from the linked list using the // deleteDuplicates function head = solution.deleteDuplicates(head); // Print the linked list after removing duplicates System.out.println( "After removing duplicates linked list is:"); ListNode curr = head; while (curr != null) { System.out.print(curr.val + " "); curr = curr.next; } System.out.println(); } } ``` C# ```using System; using System.Collections.Generic; // Define a node in a linked list class ListNode { // Value of the node public int val; // Pointer to the next node in the linked list public ListNode next; public ListNode(int x) { this.val = x; this.next = null; } } class Solution { // Remove duplicates from sorted linked list using set public ListNode DeleteDuplicates(ListNode head) { // Return head if it's empty if (head == null) return head; // Use set to store unique values in linked list HashSet<int> set = new HashSet<int>(); // Pointer to traverse the linked list ListNode curr = head; // Pointer to keep track of the previous node ListNode prev = null; // Iterate through the linked list while (curr != null) { // If the current value already exists in set, // remove the node if (set.Contains(curr.val)) { prev.next = curr.next; } else { // Otherwise, add the value to set and move // on to the next node set.Add(curr.val); prev = curr; } curr = curr.next; } // Return the head of the linked list return head; } } class Program { static void Main(string[] args) { // Initialize linked list with values 1, 2, 2, 3 ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(2); head.next.next.next = new ListNode(2); head.next.next.next.next = new ListNode(3); head.next.next.next.next.next = new ListNode(3); head.next.next.next.next.next.next = new ListNode(3); Console.WriteLine( "Before removing duplicates linked list is:"); ListNode beforePrinter = head; while (beforePrinter != null) { Console.Write(beforePrinter.val + " "); beforePrinter = beforePrinter.next; } Console.WriteLine(); Solution solution = new Solution(); // Remove duplicates from the linked list using the // DeleteDuplicates function head = solution.DeleteDuplicates(head); // Print the linked list after removing duplicates Console.WriteLine( "after removing duplicates linked list is:"); ListNode curr = head; while (curr != null) { Console.Write(curr.val + " "); curr = curr.next; } Console.WriteLine(); } } // this code is contributed by snehalsalokhe ``` Javascript ```// javascript code addition // Define a node in a linked list class Node { constructor(x) { this.val = x; // Value of the node. this.next = null; // Pointer to the next in the linked list. } } class Solution { // Remove duplicates from sorted linked list using set deleteDuplicates(head) { // Return head if it's empty if (head == null) return head; // Use set to store unique values in linked list let set = new Set(); let curr = head; // Pointer to traverse the linked list let prev = null; // Pointer to keep track of the previous node // Iterate through the linked list while (curr) { // If the current value already exists in set, remove the node if (set.has(curr.val)) { prev.next = curr.next; } else { // Otherwise, add the value to set and move on to the next node set.add(curr.val); prev = curr; } curr = curr.next; } // Return the head of the linked list return head; } }; // Initialize linked list with values 1, 2, 2, 3 let head = new Node(1); head.next = new Node(2); head.next.next = new Node(2); head.next.next.next = new Node(2); head.next.next.next.next = new Node(3); head.next.next.next.next.next = new Node(3); head.next.next.next.next.next.next = new Node(3); let BeforePrinter = head; console.log("Before removing duplicates linked list is:"); console.log("\n"); while (BeforePrinter) { console.log(BeforePrinter.val + " "); BeforePrinter = BeforePrinter.next; } console.log("\n"); let solution = new Solution(); // Remove duplicates from the linked list using the deleteDuplicates function head = solution.deleteDuplicates(head); // Print the linked list after removing duplicates console.log("after removing duplicates linked list is:"); let curr = head; console.log("\n"); while (curr) { console.log(curr.val + " "); curr = curr.next; } console.log("\n"); console.log(); // This code is contributed by Nidhi goel. ``` Python3 ```# Define a node in a linked list class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: # Return head if it's empty if not head: return head # Use set to store unique values in linked list unique_vals = set() curr = head # Pointer to traverse the linked list prev = None # Pointer to keep track of the previous node # Iterate through the linked list while curr: # If the current value already exists in set, remove the node if curr.val in unique_vals: prev.next = curr.next else: # Otherwise, add the value to set and move on to the next node unique_vals.add(curr.val) prev = curr curr = curr.next # Return the head of the linked list return head # Initialize linked list with values 1, 2, 2, 3 head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(2) head.next.next.next = ListNode(2) head.next.next.next.next = ListNode(3) head.next.next.next.next.next = ListNode(3) head.next.next.next.next.next.next = ListNode(3) BeforePrinter = head print("Before removing duplicates linked list is:") while BeforePrinter: print(BeforePrinter.val, end=" ") BeforePrinter = BeforePrinter.next print() solution = Solution() # Remove duplicates from the linked list using the deleteDuplicates function head = solution.deleteDuplicates(head) # Print the linked list after removing duplicates print("After removing duplicates linked list is:") curr = head while curr: print(curr.val, end=" ") curr = curr.next print() ```

Output
```Before removing duplicates linked list is:
1 2 2 2 3 3 3
after removing duplicates linked list is:
1 2 3 ```

Time Complexity: O(n)
Auxiliary Space: O(n)

Previous
Next