Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In this question, I need to remove the duplicate elements of the linked list. But it is generating error in some of the test cases(to be specific in those cases where the duplicate element occurs at the end of the linked list). Can someone help me figure out the error?

What I have tried:

SinglyLinkedListNode* removeDuplicates(SinglyLinkedListNode* llist)
{
    if(llist==NULL)
    return NULL;
    
    SinglyLinkedListNode* curr=llist;
    while(curr!=NULL && curr->next!=NULL)
    {
        SinglyLinkedListNode* temp=curr;
        while(temp->next!=NULL)
        {
            if(temp!=NULL && temp->next->data==curr->data)
            {
                SinglyLinkedListNode* nodetodelete=temp->next;
                temp->next=temp->next->next;
                delete(nodetodelete);
            }
            temp=temp->next;
        }
        curr=curr->next;
    }
    return llist;
}
Posted
Updated 22-Aug-22 16:42pm
Comments
Rick York 21-Aug-22 22:17pm    
In my opinion, the easiest way is to not let them be added in the first place.

At the end of the list, temp->next will be null to indicate the end of the list.
So this code:
C++
if(temp!=NULL && temp->next->data==curr->data)
will always fail for the last item as the next item doesn't exist.

Frankly, I'm not at all sure what temp->next->data==curr->data is supposed to be checking for, so I can't suggest a fix. I'd go back to the original instructions and check that part fairly carefully.
 
Share this answer
 
Shouldn't the reference to the next element be better in the else branch?
C
if(temp!=NULL && temp->next->data==curr->data)
{
  SinglyLinkedListNode* nodetodelete=temp->next;
  temp->next=temp->next->next;
  delete(nodetodelete);
}
else
  temp=temp->next;
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900