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

LeetCode合并两个有序链表:JavaScript代码逻辑错误求助

题目描述
  1. 合并两个有序链表(Merge Two Sorted Lists)
    给定两个有序链表list1和list2的头节点,将这两个链表合并为一个有序链表,新链表需通过拼接前两个链表的节点组成,返回合并后链表的头节点。
问题与代码

我正在解决该LeetCode问题,但搞不懂自己的JavaScript代码逻辑哪里错了!

以下是我的代码:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    let head = new ListNode()
    let temp = head
    while(list1 && list2){
        if(list1.val>list2.val){
            head.next = list2
            list2 = list2.next
        }
        if(list1.val <= list2.val){
            head.next = list1
            list1 = list1.next
        }
        head = head.next
    }
    if(list1){
        head.next = list1
    }
    if(list2){
        head.next = list2
    }
    return temp.next
};

测试用例:
测试用例

问题分析与修正

你的代码核心问题在于两个if语句没有互斥:
当第一个if条件(list1.val > list2.val)成立时,你会把head.next指向list2并移动list2指针,但紧接着第二个if(list1.val <= list2.val)会再次判断——此时list2已经移动到下一个节点,这个条件很可能依然成立,于是你会把head.next重新指向list1,直接覆盖了之前对list2节点的引用,导致list2的当前节点被跳过,最终合并后的链表缺失部分节点。

只需要把第二个if改成else if,让两个分支互斥即可:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function(list1, list2) {
    let head = new ListNode()
    let temp = head
    while(list1 && list2){
        if(list1.val > list2.val){
            head.next = list2
            list2 = list2.next
        } else if(list1.val <= list2.val){ // 改为else if,保证二选一
            head.next = list1
            list1 = list1.next
        }
        head = head.next
    }
    // 简化剩余节点处理逻辑
    head.next = list1 || list2
    return temp.next
};

另外最后处理剩余节点的部分,也可以简化为head.next = list1 || list2,逻辑和原来一致但更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:45:53