# Remove duplicates from a sorted linked list

Write a 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 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 data of next node is same as current node then delete the next node. Before we delete a node, we need to store next pointer of the node

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

## C

 `/* C Program to remove duplicates from a sorted linked list */` `#include ` `#include ` ` `  `/* 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 beginging 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 off 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; ` `    ``} ` `}  ` ` `  `/* Drier 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``(````" Linked list before duplicate removal  "````); ` `    ``printList(head);  ` ` `  `    ``/* Remove duplicates from linked list */` `    ``removeDuplicates(head);  ` ` `  `    ``printf``(````" Linked list after duplicate removal "````);          ` `    ``printList(head);             ` `   `  `    ``return` `0; ` `} `

## Java

 `// Java program to remove duplicates from a sorted linked list ` `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 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``) ` `         ``{ ` `            ``System.out.print(temp.data+``" "``); ` `            ``temp = temp.next; ` `         ``}   ` `         ``System.out.println(); ` `     ``} ` ` `  `     ``/* Drier 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 */`

## Python 3

 `# 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  ` `    ``# occurence 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. `

## 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 */`

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 number of nodes in the given linked list.

Recursive Approach :

 `/* C recursive Program to remove duplicates from a sorted linked list */` `#include ` `#include ` ` `  `/* Link list node */` `struct` `Node ` `{ ` `    ``int` `data; ` `    ``struct` `Node* next; ` `}; ` `/* UTILITY FUNCTIONS */` `/* Function to insert a node at the beginging 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 off 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; ` `    ``} ` `}  ` ` `  ` ``Node* deleteDuplicates(Node* head) { ` `        ``if` `(head == nullptr) ``return` `nullptr; ` `        ``if` `(head->next == nullptr) ``return` `head; ` ` `  `        ``if` `(head->data == head->next->data) { ` `            ``Node *tmp; ` `            ``// If find next element duplicate, preserve the next pointer to be deleted,  ` `            ``// skip it, and then delete the stored one. Return head ` `            ``tmp = head->next; ` `            ``head->next = head->next->next; ` `            ``free``(tmp); ` `            ``return` `deleteDuplicates(head); ` `        ``} ` ` `  `        ``else` `{ ` ` `  `            ``// if doesn't find next element duplicate, leave head  ` `            ``// and check from next element ` `            ``head->next = deleteDuplicates(head->next); ` `            ``return` `head; ` `        ``} ` `    ``} ` ` `  `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``(````" Linked list before duplicate removal  "````); ` `    ``printList(head);  ` ` `  `    ``/* Remove duplicates from linked list */` `    ``head = deleteDuplicates(head);  ` ` `  `    ``printf``(````" Linked list after duplicate removal "````);          ` `    ``printList(head);             ` `   `  `    ``return` `0; ` `} ` `/* This code is contributed by Yogesh shukla */`

output

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

Related Article :
Remove all occurrences of duplicates from a sorted Linked List

This article is attributed to GeeksforGeeks.org

code

load comments