142. 环形链表 II 我这么写为什么有个 case 无法通过

215 天前
 sugarkeek

感觉也没啥区别呀

我的代码:

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != slow){
            if(fast == null || fast.next == null){
                return null;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        fast = head;
        while( fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}

无法通过的 case:

输入
[3,2,0,-4]
1
输出
tail connects to node index 0
预期结果
tail connects to node index 1

可以通过的代码:

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        while(true){
            if(fast == null || fast.next == null){
                return null;
            }
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow) break;
         }
        fast = head;
        while( fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
600 次点击
所在节点    LeetCode
2 条回复
j1132888093
215 天前
你这么写条件的话,把 while 改成 do while
013231
215 天前
你的问题出在第一个循环条件的判断上。
在你的代码中,你在使用“快慢指针法”寻找环的时候,你的循环条件为 while(fast != slow),意味着只有当 fast 和 slow 指针相等时才跳出循环。然而,这在 fast 和 slow 指针第一次初始化时就已经满足,因此你的循环根本没有执行。这导致你在后面的代码中错误地认为 fast 和 slow 指针已经找到环,并试图从头开始寻找环的入口,结果找到的是链表的头部,因为 fast 和 slow 指针都没有移动过。
================================
上面的话是 GPT 4 说的。我支持 GPT 的观点。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/979777

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX