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

C语言合并两个有序链表测试用例失败问题咨询

C语言合并两个有序链表测试用例失败问题咨询

嘿,我懂你为啥这个测试用例失败啦!你看哦,当list1 = []、list2 = [0]的时候,你的代码里那个while(temp1 != NULL && temp2 != NULL)的循环条件根本就不成立——因为temp1一开始就是NULL,循环直接跳过了。而你写的那个判断if(temp1 != NULL && temp2 == NULL)还放在循环里面,自然也不会执行,最后result一直是NULL,返回的就是空链表,但正确结果应该是返回list2的那个[0]节点呀!

咱们来梳理下问题出在哪:你的代码只处理了两个链表都有节点的情况,完全没考虑其中一个链表一开始就是空的场景,也没处理循环结束后剩下的非空链表节点。

给你个修改思路,先把边界情况处理掉,再完善循环内的逻辑:

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    // 先直接处理其中一个链表为空的情况
    if (list1 == NULL) return list2;
    if (list2 == NULL) return list1;

    struct ListNode* result = NULL;
    struct ListNode* tail = NULL; // 用这个指针跟踪结果链表的尾部,方便拼接
    struct ListNode* temp1 = list1;
    struct ListNode* temp2 = list2;

    while(temp1 != NULL && temp2 != NULL){
        if(temp1->val <= temp2->val){
            if(result == NULL){
                // 初始化结果链表的头节点
                result = temp1;
                tail = temp1;
            } else {
                // 把当前节点接到结果链表尾部
                tail->next = temp1;
                tail = tail->next;
            }
            temp1 = temp1->next;
        } else {
            if(result == NULL){
                result = temp2;
                tail = temp2;
            } else {
                tail->next = temp2;
                tail = tail->next;
            }
            temp2 = temp2->next;
        }
    }

    // 循环结束后,把剩下的非空链表直接接到结果尾部
    if(temp1 != NULL){
        tail->next = temp1;
    }
    if(temp2 != NULL){
        tail->next = temp2;
    }

    return result;
}

你看,开头的两个if就直接解决了你遇到的测试用例问题——当list1为空时,直接返回list2,完美符合预期。另外加了个tail指针,避免每次找结果链表的尾部,效率更高;循环结束后还把剩下的节点接上,也覆盖了其中一个链表更长的情况。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 13:29:52