Reputation: 1
I'm trying to delete duplicate values from a sorted singly linked list.
this is my code
SinglyLinkedListNode* removeDuplicates(SinglyLinkedListNode* head) {
if(head==NULL)
return head;
int flag=0;
SinglyLinkedListNode* p,*q,*temp;
for(p=head;p->next!=NULL;p=p->next)
{
if(flag==1)
{
p=temp;
flag=0;
}
q=p->next;
if(q->data==p->data)
{
temp=p;
p->next=q->next;
free(q);
flag=1;
}
}
return head;
}
However the code fails when Singly linked list is 3->3->3->4->5->5->NULL
Upvotes: 0
Views: 34
Reputation: 249
Please try this code-
void removeDuplicates(SinglyLinkedListNode* head)
{
SinglyLinkedListNode* current = head;
SinglyLinkedListNode* nextNode;
if (current == NULL)
return;
while (current->next != NULL)
{
if (current->data == current->next->data)
{
nextNode = current->next->next;
free(current->next);
current->next = nextNode;
}
else
{
current = current->next;
}
}
}
Upvotes: 1