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

链表遍历与尾部插入中temp!=null和temp.next!=null的区别

链表遍历与尾部插入的while循环核心区别

核心目标差异是根源

两种循环的写法差异,完全源于各自的目标不同:

  • 遍历链表的目标是逐个访问所有节点,不能漏掉任何一个;
  • 尾部插入的目标是定位到最后一个节点,把新节点挂在它后面,不需要走到空指针。

具体区别拆解

  • 终止条件的本质

    • 遍历用while (temp != null):循环会持续到temp指向null(也就是走完了所有节点)。每一轮循环里,我们操作的就是当前temp指向的节点,确保每个节点都被处理到。
    • 尾部插入用while (temp.next != null):循环在temp.next为null时停止,这时temp正好是链表的最后一个节点,直接给temp.next赋值新节点就能完成插入。
  • 代码执行逻辑对比
    遍历的典型代码:

    ListNode temp = head;
    while (temp != null) {
        // 处理当前节点,比如打印值、修改数据
        System.out.println(temp.val);
        temp = temp.next;
    }
    

    尾部插入的典型代码:

    ListNode temp = head;
    while (temp.next != null) {
        temp = temp.next;
    }
    // 此时temp是最后一个节点,直接挂新节点
    temp.next = new ListNode(newValue);
    
  • 用反的后果

    • 如果遍历用temp.next != null:会漏掉最后一个节点的处理,因为循环在倒数第二个节点就停止了;
    • 如果尾部插入用temp != null:最后temp会变成null,这时候给temp.next赋值会触发空指针异常,根本插不了新节点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:48:17