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

LeetCode链表环路II问题:Floyd环路算法代码运行异常求助

问题分析与修复

你的代码两个问题的根源都是第一个while循环的逻辑错误:

问题1:直接返回head的原因

初始时slow和fast都指向head,循环条件slow!=fast一开始就不成立,循环体完全不会执行,直接进入后续逻辑。此时whereIsCollision和slow都等于head,第二个循环的条件也不成立,直接返回head。

问题2:if判断从未触发

因为第一个while循环根本没执行,里面的空指针检测逻辑自然不会被触发,无法正确识别无环链表。

修复后的代码

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) return null;
        
        ListNode slow = head;
        ListNode fast = head;
        // 先保证fast不越界,再移动指针,最后判断是否相遇
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            // 相遇则退出循环,进入环入口检测
            if (slow == fast) {
                break;
            }
        }
        
        // 循环退出后检查是否无环
        if (fast == null || fast.next == null) {
            return null;
        }
        
        // 寻找环的入口节点
        ListNode whereIsCollision = head;
        while (whereIsCollision != slow) {
            whereIsCollision = whereIsCollision.next;
            slow = slow.next;
        }
        return whereIsCollision;
    }
}

修复说明

  • 调整第一个循环逻辑:先判断fast和fast.next是否为空(避免空指针异常),再移动快慢指针,最后检测是否相遇。
  • 单独处理无环情况:循环结束后,如果fast或fast.next为空,说明链表无环,直接返回null。
  • 保留原环入口检测逻辑:快慢指针相遇后,将其中一个指针移到链表头部,两个指针同速移动,相遇点即为环的入口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:32:47