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

反转链表调试遇Cannot read property 'next' of undefined错误,如何解决?

解决反转链表时的Cannot read property 'next' of undefined错误

嘿,我来帮你揪出这个问题的根源!你遇到的报错其实是因为链表构建不规范导致的,咱们一步步拆解来看:

错误原因分析

先看你构建的链表结构:你创建了n4 = {val: null},然后让n3.next = n4——但标准的链表尾节点应该是next属性为null,而不是用一个val为null的节点来充当尾巴。这会让循环执行到最后阶段出问题:

咱们走一遍循环的执行流程:

  1. 前三次循环都正常:head依次指向n1、n2、n3,每次都能正确获取nextNode,更新指针关系。
  2. 第四次循环:head变成n4,但n4没有定义next属性,所以head.next的值是undefined。执行完本轮后,head被赋值为undefined。
  3. 第五次循环:你的循环条件是head !== null,但undefined和null是两个不同的值,条件判断为true,会继续进入循环。这时候执行let nextNode = head.next,就会试图读取undefined的next属性,直接抛出TypeError。

修复方案

方案一:规范构建链表(推荐)

直接把链表的尾节点next设为null,不需要创建n4这个多余的节点:

var reverseList = function(head) { 
  let prevNode = null 
  while (head !== null) { 
    let nextNode = head.next; 
    head.next = prevNode 
    prevNode = head; 
    head = nextNode; 
  } 
  return prevNode; 
}; 

const n1 = {val: 4} 
const n2 = {val: 7} 
const n3 = {val: 1} 
n1.next = n2; 
n2.next = n3; 
n3.next = null; // 直接设置为null,作为链表的结尾
reverseList(n1)

方案二:兼容循环条件(可选)

如果你一定要保留n4的形式,记得给它加上next: null属性,同时把循环条件改成while (head)(这样会自动过滤null和undefined):

var reverseList = function(head) { 
  let prevNode = null 
  while (head) { // 改成这个条件,判断head是否为真值
    let nextNode = head.next; 
    head.next = prevNode 
    prevNode = head; 
    head = nextNode; 
  } 
  return prevNode; 
}; 

const n1 = {val: 4} 
const n2 = {val: 7} 
const n3 = {val: 1} 
const n4 = {val: null, next: null} // 给n4补上next属性
n1.next = n2; 
n2.next = n3; 
n3.next = n4; 
reverseList(n1)

调试小技巧

以后调试链表问题时,你可以在循环里加console.log打印每一步的head.val、prevNode和nextNode,这样能直观看到每一轮循环的变量变化,快速定位问题~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:22:41