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

JavaScript实现链表printlist()方法打印结果为undefined问题求解

问题原因

你的代码打印undefined是几个逻辑错误共同导致的:

  • 每个Node实例里错误定义了this.head = null属性,调用n1.printlist()时,方法内取的this.head默认就是null,while循环完全不会执行
  • 遍历起始节点写错:从头节点n1调用打印方法时,遍历的第一个节点应该是当前实例this,而非不存在有效值的this.head
  • 调用getNextNode()时多余传入了this.next参数,该方法本身无参,直接返回当前节点的next指向即可
  • printlist()方法没有设置返回值,外层执行console.log(n1.printlist())时,无返回值的函数默认返回undefined,就会打印出undefined
  • 额外逻辑瑕疵:你把console.log(output)写在了循环内部,会逐次打印累加过程的中间字符串,不符合一次性打印完整链表的需求;同时head是链表级别的头指针,不应该挂载在每个独立节点上,节点只需要存自身数据和后继节点指针即可。
修复后的可运行代码
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
  setNextNode(node) {
    this.next = node;
  }

  getNextNode() {
    return this.next;
  }

  printlist() {
    let current = this;
    let output = "";
    while (current !== null) {
      output += current.data + ' ';
      current = current.getNextNode();
    }
    return output.trim();
  }
}

const n1 = new Node(1);
const n2 = new Node(2);
const n3 = new Node(3);
n1.setNextNode(n2);
n2.setNextNode(n3);

console.log(n1.printlist()); // 运行输出: 1 2 3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 16:09:21