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

如何实现数组元素去重后添加到链表?现有代码去重失效求助

链表去重插入问题修复

你的代码核心问题出在makeList函数的逻辑上,导致重复值没有被过滤,具体问题和修复方案如下:

问题分析

  1. 遍历指针未重置:原代码中tmp2仅在函数开头初始化一次,第一次循环后tmp2会走到链表末尾变为NULL,后续循环中tmp2一直是NULL,完全跳过了重复检查的逻辑。
  2. 重复检查逻辑错误:原代码只要链表节点值不等于当前数组元素就执行插入,这会导致同一个元素被多次插入,完全没有实现去重的效果。

修复后的代码

修正后的makeList函数

void makeList(int arr[], int len, TNode *head) {
    for (int i = 0; i < len; i++) {
        // 遍历链表检查当前元素是否已存在
        TNode current = *head;
        int is_duplicate = 0;
        while (current != NULL) {
            if (current->data == arr[i]) {
                is_duplicate = 1;
                break; // 找到重复,终止检查
            }
            current = current->next;
        }
        
        // 仅当元素不存在时,插入到链表头部(保持原代码的插入方式)
        if (!is_duplicate) {
            TNode new_node = (TNode)malloc(sizeof(SNode));
            new_node->data = arr[i];
            new_node->next = *head;
            *head = new_node;
        }
    }
}

额外修正:main函数返回值

C标准要求main函数的返回类型为int,修正后:

int main() {
    TNode head = NULL;
    int array[5] = { 1, 2, 4, 4, 8 };
    
    makeList(array, 5, &head);
    
    printList(head);
    return 0;
}

运行效果

修复后运行代码,输出结果为 8 4 2 1 (由于采用头部插入,元素顺序与原数组相反),且不存在重复的4,符合去重要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:35:27