Aaron Imani
Aaron Imani

Reputation: 23

Removing duplicate nodes from a sorted linkedlist with a simple code

I'm trying to write a method to delete duplicate nodes from a sorted linkedlist. If the method gets the input linkedlist : 1->1->2->2->3->3 it should make the linkedlist like 1->2->3 . but the problem is it returns 1->1->2->3 that means the first duplicate element is not determined ! here is my code :

void removeDuplicates(Node head)
{
  Node* Current = &head;
  while(Current != NULL && Current->next != NULL)
  {
    while(Current->next != NULL && Current->next->info == Current->info)
        Current->next = Current->next->next;

    Current=Current->next;
  }
}

whole code added : https://paste.ubuntu.com/p/hstGyDJrkN/

Upvotes: 0

Views: 160

Answers (2)

Ratah
Ratah

Reputation: 302

An alternative is to use c++ algorithm

std::unique

as shown here http://en.cppreference.com/w/cpp/algorithm/unique

You just have to furnish a good

binary predicate

which returns ​true if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following:

bool binaryPredicate(const  Node& a, const  Node& b);

Upvotes: 0

Andrew Kashpur
Andrew Kashpur

Reputation: 746

you pass head by value, so you create copy of head Node, and change next field of copy, not original head pointer. You should pass pointer by reference, so your signature should look like

void removeDuplicates(Node* &head)

so you will modify actual head pointer

Upvotes: 4

Related Questions