You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未排序链表去重代码输出不完整仅返回首个节点如何修复?

代码存在的问题

  • 多余的链表反转操作:未排序链表去重不需要预先反转链表,这部分逻辑冗余,还打乱了原始链表的节点顺序。
  • 相等判断逻辑错误:if(temp->data=temp->next->data) 中使用了赋值运算符=而非比较运算符==,会直接修改当前节点的值,且只要赋值结果非0就会判定为条件成立。
  • 遍历指针未移动:去重的循环中没有对temp指针进行后移操作,循环会一直停留在头节点位置,不断删除后续所有节点,最终只会保留头节点。
  • 去重逻辑不适用于未排序链表:当前的去重逻辑只能处理已排序链表的相邻重复节点,未排序链表的重复节点不一定相邻,这套逻辑无法覆盖非相邻的重复场景。

正确实现

哈希表法(时间复杂度O(n),空间复杂度O(n))

最常用的高效实现,用哈希集合存储已经出现过的节点值,遍历过程中直接删除重复节点:

#include <unordered_set>
Node * removeDuplicates( Node *head) 
{
    // 空链表直接返回
    if (head == NULL) return head;
    std::unordered_set<int> existed;
    Node *cur = head;
    existed.insert(cur->data);
    while (cur->next != NULL) {
        // 下一个节点的值已存在,直接删除
        if (existed.count(cur->next->data)) {
            cur->next = cur->next->next;
        } else {
            // 新值存入集合,指针后移
            existed.insert(cur->next->data);
            cur = cur->next;
        }
    }
    return head;
}

双重循环法(时间复杂度O(n²),空间复杂度O(1))

如果场景限制不能使用额外存储空间,可以改用双重循环暴力去重:

Node * removeDuplicates( Node *head) 
{
    if (head == NULL) return head;
    Node *cur = head;
    // 外层遍历每个节点
    while (cur != NULL) {
        Node *inner = cur;
        // 内层遍历删除后续所有和当前节点值重复的节点
        while (inner->next != NULL) {
            if (inner->next->data == cur->data) {
                inner->next = inner->next->next;
            } else {
                inner = inner->next;
            }
        }
        cur = cur->next;
    }
    return head;
}

内容的提问来源于stack exchange,提问作者NAMAN VERMA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:18:02