Remove duplicates from a sorted linked list using recursion - GeeksforGeeks

24 Jun, 2021
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 to 11->21->43->60.  
Algorithm: Traverse the list recursively from the head (or start) to end and after completion of recursion calls, compare the next node(returned node) and current node(head). If data of both nodes are equal then return the next (head-> next) node else return the current node(head).Implementation: Functions other than removeDuplicates() are just to create a linked linked list and test removeDuplicates().  
C++
Java
Python
C#
Javascript
/* C Program to remove duplicates from a sorted linked list */#include <bits/stdc++.h>#include <stdlib.h> /* Link list node */struct Node {    int data;    struct Node* next;}; /* The function removes duplicates from a sorted list */struct Node* removeDuplicates(struct Node* head){    /* if head is null then return*/    if (head == NULL)        return NULL;     /* Remove duplicates from list after head */    head->next = removeDuplicates(head->next);     // Check if head itself is duplicate    if (head->next != NULL &&        head->next->data == head->data) {         Node* res = head->next;        delete head;        return res;    }     return head;} /* UTILITY FUNCTIONS *//* Function to insert a node at   the beginning of the linked list */void push(struct Node** head_ref, int new_data){    struct Node* new_node = new Node;    new_node->data = new_data;    new_node->next = (*head_ref);    (*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 ");    printList(head);     /* Remove duplicates from linked list */    struct Node* h = removeDuplicates(head);     printf("\n Linked list after duplicate removal ");    printList(h);     return 0;}
/* Java Program to remove duplicatesfrom a sorted linked list */class GFG{ /* Link list node */static class Node{    int data;    Node next;}; /* The function removes duplicates from a sorted list */static Node removeDuplicates( Node head){    /* if head is null then return*/    if (head == null)        return null;     /* Remove duplicates from list after head */    head.next = removeDuplicates(head.next);     // Check if head itself is duplicate    if (head.next != null &&        head.next.data == head.data)    {         Node res = head.next;                 return res;    }     return head;} /* UTILITY FUNCTIONS *//* Function to insert a node atthe beginning of the linked list */static Node push( Node head_ref, int new_data){    Node new_node = new Node();    new_node.data = new_data;    new_node.next = (head_ref);    (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.printf("%d ", node.data);        node = node.next;    }} /* Driver program to test above functions*/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.printf("\n Linked list before duplicate removal ");    printList(head);     /* Remove duplicates from linked list */    Node h = removeDuplicates(head);     System.out.printf("\n Linked list after duplicate removal ");    printList(h);}} // This code is contributed by Arnab Kundu
# Python Program to remove duplicates# from a sorted linked list # A linked list nodeclass Node:    def __init__(self, new_data):        self.data = new_data        self.next = None # The function removes duplicates from a sorted listdef removeDuplicates( head) :     # if head is None then return    if (head == None) :        return None     # Remove duplicates from list after head    head.next = removeDuplicates(head.next)     # Check if head itself is duplicate    if (head.next != None and        head.next.data == head.data):        res = head.next                 return res         return head # UTILITY FUNCTIONS# Function to insert a node at#the beginning of the linked listdef push( head_ref, new_data) :    new_node = Node(0)    new_node.data = new_data    new_node.next = (head_ref)    (head_ref) = new_node    return head_ref # Function to print nodes in a given linked listdef printList(node) :     while (node != None) :             print(node.data,end=" ")        node = node.next     # Driver program to test above functions # Start with the empty listhead = None # Let us create a sorted linked list to test the functions# Created linked list will be 11.11.11.13.13.20head = push(head, 20)head = push(head, 13)head = push(head, 13)head = push(head, 11)head = push(head, 11)head = push(head, 11) print("\n Linked list before duplicate removal ")printList(head) # Remove duplicates from linked listh = removeDuplicates(head) print("\n Linked list after duplicate removal ")printList(h) # This code is contributed by Arnab Kundu
/* C# Program to remove duplicatesfrom a sorted linked list */using System; class GFG{         /* Link list node */    public class Node    {        public int data;        public Node next;    };         /* The function removes duplicates from a sorted list */    static Node removeDuplicates( Node head)    {        /* if head is null then return*/        if (head == null)            return null;             /* Remove duplicates from list after head */        head.next = removeDuplicates(head.next);             // Check if head itself is duplicate        if (head.next != null &&            head.next.data == head.data)        {                 Node res = head.next;                         return res;        }             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)    {        Node new_node = new Node();        new_node.data = new_data;        new_node.next = (head_ref);        (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("{0} ", node.data);            node = node.next;        }    }         /* Driver program to test above functions*/    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);             Console.Write("\n Linked list before duplicate removal ");        printList(head);             /* Remove duplicates from linked list */        Node h = removeDuplicates(head);             Console.Write("\n Linked list after duplicate removal ");        printList(h);    }} /* This code contributed by PrinciRaj1992 */
<script>       /* JavaScript Program to remove duplicates         from a sorted linked list */      /* Link list node */      class Node {        constructor() {          this.data = 0;          this.next = null;        }      }       /* The function removes duplicates from a sorted list */      function removeDuplicates(head) {        /* if head is null then return*/        if (head == null) return null;         /* Remove duplicates from list after head */        head.next = removeDuplicates(head.next);         // Check if head itself is duplicate        if (head.next != null && head.next.data == head.data) {          var res = head.next;           return res;        }         return head;      }       /* UTILITY FUNCTIONS */      /* Function to insert a node at    the beginning of the linked list */      function push(head_ref, new_data) {        var new_node = new Node();        new_node.data = new_data;        new_node.next = head_ref;        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 program to test above functions*/      /* 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 ");      printList(head);       /* Remove duplicates from linked list */      var h = removeDuplicates(head);       document.write("<br> Linked list after duplicate removal ");      printList(h);       </script>
Linked list before duplicate removal 11 11 11 13 13 20 
 Linked list after duplicate removal 11 13 20
 
andrew1234
princiraj1992
nidhi_biet
rdtank
Linked List
Recursion
Linked List
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction