为何寻找链表中间节点的代码中fast.next会抛出TypeError?
链表中间节点代码的TypeError错误原因解析
先看你提供的代码:
const middleNode = (head) => { let fast = head let slow = head if (head !== null) { while (fast.next !== null) { fast = fast.next.next slow = slow.next } } return slow }
这个代码之所以会抛出「TypeError: Cannot read properties of null (reading 'next')」,核心问题出在循环条件的判断逻辑有漏洞:
- 循环条件只检查了
fast.next !== null,但没有先确认fast本身是不是null。 - 当链表的节点数为偶数时,执行
fast = fast.next.next后,fast会变成null(比如链表是1->2,第一次循环后fast就变成2.next = null)。此时下一轮循环判断fast.next时,相当于访问null.next,自然会触发报错——因为null对象根本没有next属性。
举个具体的例子(链表为1->2):
- 初始状态:
fast = 1,slow = 1,head不为空,进入循环。 - 第一次循环判断:
fast.next是2,不为null,进入循环体。 - 执行
fast = fast.next.next,也就是1.next.next = 2.next = null;slow变成2。 - 回到循环条件判断:此时
fast已经是null,执行fast.next就会直接抛出类型错误。
要修复这个问题,只需要把循环条件改成while (fast !== null && fast.next !== null)——先判断fast是否为null,再去访问它的next属性,就能避免空指针访问的问题。
内容的提问来源于stack exchange,提问作者user20977536
相关产品推荐
相关产品推荐

