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

LeetCode 2. Add Two Numbers:调用reverse()为何报错?

LeetCode 2. Add Two Numbers 问题解答

为什么reverse()调用报错?

别被示例里的[2,4,3]误导——LeetCode传入的l1和l2根本不是JavaScript数组,而是题目定义的链表节点对象,结构大概是这样:

function ListNode(val, next) {
  this.val = val ?? 0;
  this.next = next ?? null;
}

这种链表节点没有数组的reverse()方法,直接调用当然会报reverse is not a function。

你的代码还有这些坑

  • concat()是返回新字符串,不会修改原变量,得写成l1temp = l1temp.concat(l1[i]),不然l1temp永远是空的。
  • parseInt(l1temp)没赋值给变量,等于白写,根本不会把字符串转成数字。
  • l2temp + l1temp是字符串拼接,不是数字相加,比如"342"+"465"会得到"342465",不是807。
  • const array声明后不能重新赋值,array = hello.split('')会直接报错。
  • 题目要求返回链表节点,你最后返回数组,完全不符合要求。

正确的解法:直接操作链表模拟加法

不用转数字,直接按加法进位逻辑遍历链表就行:

var addTwoNumbers = function(l1, l2) {
    const dummyHead = new ListNode(0);
    let current = dummyHead;
    let carry = 0;
    
    while (l1 !== null || l2 !== null || carry !== 0) {
        const val1 = l1 ? l1.val : 0;
        const val2 = l2 ? l2.val : 0;
        const sum = val1 + val2 + carry;
        
        carry = Math.floor(sum / 10);
        current.next = new ListNode(sum % 10);
        current = current.next;
        
        l1 = l1?.next ?? null;
        l2 = l2?.next ?? null;
    }
    
    return dummyHead.next;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:54:23