Open In App

Remove duplicates from a sorted linked list using recursion

Last Updated : 12 Jan, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report

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 list and test removeDuplicates(). 

C++
Java Python C# JavaScript

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

 

Time Complexity: O(N), to traverse n nodes in the Linked List
Auxiliary Space: O(N), to store n nodes in the Linked List.


Next Article
Article Tags :
Practice Tags :

Similar Reads