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

为何我的count变量无法输出正确结果?链表求和结果异常排查

链表求和count变量输出错误的解决方法

你的问题出在JavaScript的基本类型按值传递特性上:count是数字类型,属于基本类型,当你把它作为参数传给sum函数时,传递的是当前值的副本,sum函数里对count的修改只会作用于这个副本,不会影响sumList中声明的原count变量,所以最终返回的始终是初始值0。

下面提供两种修复方案:

方案1:让递归函数返回累加总和

这种方式更符合递归的设计思路,直接让递归函数返回当前节点值加上后续节点的总和:

class Node {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

const a = new Node(2);
const b = new Node(8);
const c = new Node(3);
const d = new Node(-1);
const e = new Node(7);

a.next = b;
b.next = c;
c.next = d;
d.next = e;

const head = a

const sumList = (head) => {
  return sum(head);
}

const sum = (head) => {
  // 空节点返回0,作为累加的基准值
  if (head === null) return 0;
  // 返回当前节点值 + 后续所有节点的总和
  return head.val + sum(head.next);
}

console.log(sumList(head)); // 输出15

方案2:用引用类型传递累加值

如果要保留原有的函数结构,可以用对象(引用类型)来封装count,因为引用类型传递的是内存地址,修改对象的属性会影响原对象:

class Node {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

const a = new Node(2);
const b = new Node(8);
const c = new Node(3);
const d = new Node(-1);
const e = new Node(7);

a.next = b;
b.next = c;
c.next = d;
d.next = e;

const head = a

const sumList = (head) => {
  const countObj = { value: 0 };
  sum(head, countObj);
  return countObj.value;
}

const sum = (head, countObj) => {
  if (head === null) return;
  countObj.value += head.val;
  sum(head.next, countObj);
}

console.log(sumList(head)); // 输出15

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:54:19