Close

Deleting duplicate elements from a sorted linked list

Given a sorted linked list, how do we delete duplicate nodes from it?

This question is simple and straightforward, we take two pointers, current and next which points the adjacent nodes. In each iteration we compare the values at these two nodes, if they are equal, we delete the node pointed by next and advance the two pointers. Take a look at the following diagram to get better understanding.

Here is the C++ implementation

#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
};
ListNode * deleteDuplicates(ListNode *head)
{
if( !head || !(head->next))
return head;
ListNode *cPtr = head;
ListNode *nPtr = head->next;
while( nPtr )
{
if( cPtr->val == nPtr->val )
{
ListNode *temp = nPtr;
nPtr = nPtr->next;
cPtr->next = nPtr;
delete temp;
}
else
{
cPtr = nPtr;
nPtr = nPtr->next;
}
}
return head;
}
int main()
{
ListNode *head = new ListNode();
head->val = 1;
head->next = new ListNode();
head->next->val = 1;
head->next->next = NULL;
head = deleteDuplicates(head);
return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *