使用简单代码从已排序的链表中删除重复节点

Removing duplicate nodes from a sorted linkedlist with a simple code

我正在尝试编写一种方法来从排序的链表中删除重复节点。如果该方法获得输入链表: 1->1->2->2->3->3 它应该使链表像 1->2->3 。但问题是 returns 1->1->2->3 这意味着第一个重复元素未确定!这是我的代码:

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

已添加完整代码:https://paste.ubuntu.com/p/hstGyDJrkN/

你按值传递 head,所以你创建了 head 节点的副本,并更改​​了副本的下一个字段,而不是原始的 head 指针。你应该通过引用传递指针,所以你的签名应该看起来像

void removeDuplicates(Node* &head)

所以你将修改实际的头指针

另一种方法是使用 c++ 算法

std::unique

如图所示 http://en.cppreference.com/w/cpp/algorithm/unique

你只需要提供一个好的

binary predicate

which returns true 如果元素应该被视为相等。 谓词函数的签名应等效于以下内容:

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