0

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/

4
  • the_list.erase(std::unique(the_list.begin(), the_list.end()), the_list.end()); would be the usual solution to "Removing duplicate nodes from a sorted linkedlist". See std::unique Commented Mar 26, 2018 at 11:17
  • Did you notice that head is a pointer? leetcode.com/problems/remove-duplicates-from-sorted-list/… Commented Mar 26, 2018 at 11:18
  • 1
    by the way, you just "forget" nodes you want to remove from list, you do not delete object, its memory leak Commented Mar 26, 2018 at 11:20
  • std::unique could work, if the node is passed by reference instead of pointer and is provided with additional increment and comparison operators - and probably assignment, too, preferably move-assignment in given case... Commented Mar 26, 2018 at 11:23

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Did you test that before posting?
0

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);

1 Comment

std::unique will increment the pointer, though, which likely yields a different result than pointer = pointer->next; so we need some extra work to get this right...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.