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

为何寻找链表中间节点的代码中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):

  1. 初始状态:fast = 1,slow = 1,head不为空,进入循环。
  2. 第一次循环判断:fast.next是2,不为null,进入循环体。
  3. 执行fast = fast.next.next,也就是1.next.next = 2.next = null;slow变成2。
  4. 回到循环条件判断:此时fast已经是null,执行fast.next就会直接抛出类型错误。

要修复这个问题,只需要把循环条件改成while (fast !== null && fast.next !== null)——先判断fast是否为null,再去访问它的next属性,就能避免空指针访问的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:07:10