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

C语言单链表冒泡排序:sort_list正常sort_list1报错问题排查

单链表冒泡排序sort_list1崩溃原因分析及修复

崩溃根源:遍历逻辑错误导致空指针访问

sort_list1的内层循环逻辑存在致命问题:

  • 内层循环中,执行h_temp = compare_sort(h_temp)后直接h_temp = h_temp->next。但compare_sort在交换节点时,会返回交换后的当前节点(比如原本h_temp指向节点A,交换A和B后,compare_sort返回B),此时h_temp->next是A,下一次循环时相当于跳过了原本该处理的后续节点,循环次数过多时,h_temp会走到链表末尾之外,访问NULL->next触发EXC_BAD_ACCESS。
  • 反观sort_list的逻辑:通过h_temp->next = compare_sort(h_temp->next)维护链表的正确连接,之后再移动h_temp到h_temp->next,保证每次处理的都是当前节点的下一个节点,不会出现指针越界。

潜在问题:compare_sort缺少空指针校验

不管是sort_list还是sort_list1,compare_sort都没有检查h或h->next是否为NULL。当链表长度小于2,或者遍历到链表末尾时,会直接访问空指针,这是隐藏的崩溃风险。

修复后的代码

1. 修复compare_sort的空指针检查

list *compare_sort(list *h){ //compare and swap function for bubble sort
    // 空指针检查,避免访问NULL->data或NULL->next
    if (h == NULL || h->next == NULL) {
        return h;
    }
    if ((h -> data) > (h -> next -> data)){
        list *temp = h;
        h = h -> next;
        temp -> next = h -> next;
        h -> next = temp;
    }
    return h;
}

2. 修复sort_list1的遍历逻辑

把内层循环的修改方式调整为和sort_list一致,同时注意头节点的更新(冒泡排序第一轮可能会改变头节点):

list *sort_list1(list *h){ //to bubble sort the list
    int i, j;
    list *h_temp;
    for (i = 0; i < N-2; i++) {
        // 每次外层循环先处理头节点,更新头指针
        h = compare_sort(h);
        h_temp = h;
        for (j = 0; j < N-2-i; j++) {
            h_temp -> next = compare_sort(h_temp -> next);
            h_temp = h_temp ->next;
        }
    }
    return h;
}

额外说明

代码中的N是链表长度,需确保N取值正确,否则循环次数异常会引发问题。如果链表长度不确定,建议先遍历链表获取长度,而非使用固定值N。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:48:17