【问题标题】:Removing duplicates from an unsorted linked list returning incomplete output从返回不完整输出的未排序链表中删除重复项
【发布时间】:2021-11-23 21:32:34
【问题描述】:

我遇到了从未排序的链表中删除重复项的问题。我的代码没有返回我需要的输出。

Node * removeDuplicates( Node *head) 
{
    Node *cur=head;
    Node *prev=NULL;
    Node *nextptr;
    while(cur!=NULL){
        nextptr=cur->next;
        cur->next=prev;
        prev=cur;
        cur=nextptr;
    }
    head=prev;
    Node *temp=head;
    while(temp->next!=NULL){
        if(temp->data=temp->next->data){
            temp->next=temp->next->next;
        }
    }
    return head;
}

给出的链表是5->2->2->4->NULL。 这是用于从未排序的链表中删除重复项的代码。它的返回类型是一个指针。我没有得到所需的输出。所需的输出是5->2->4->NULL,但我的输出只有5。请帮助我正确的代码。

【问题讨论】:

标签: c++ algorithm data-structures linked-list logic


【解决方案1】:

有这些问题:

  • 您在赋值,而不是比较if 语句中的数据。所以改变:

    if(temp->data=temp->next->data){
    

    到:

    if(temp->data==temp->next->data){
    
  • 当该比较为假时,循环体中不会发生任何其他事情,因此while 循环将被卡住。您应该移动temp 指针。所以添加一个else 块:

    } else {
        temp = temp->next;
    }
    

其他一些评论:

  • 不要用NULL比较/初始化指针,而是用nullptr
  • 函数的第一部分反转列表。这似乎与函数的目的无关,因此省略。

更正:

Node * removeDuplicates( Node *head) {
    Node *temp=head;
    while (temp->next != nullptr) {
        if (temp->data == temp->next->data) {
            temp->next = temp->next->next;
        } else {
            temp = temp->next;
        }
    }
    return head;
}

【讨论】:

    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    相关资源
    最近更新 更多