CS-Notes全部笔记在阅读器中打开

23. 链表中环的入口结点

Leetcode

题目描述

一个链表中包含环,请找出该链表的环的入口结点。要求不能使用额外的空间。

解题思路

使用快慢指针分两个阶段:

第二阶段成立的原因如下。设头节点到入口的距离为 a,入口到相遇点的距离为 b,相遇点继续走到入口的距离为 c,环长 L = b + c。

a = (k - 1)L + c 说明:从头节点走 a 步到达入口时,从相遇点出发的指针恰好走了 c 步再绕 k - 1 圈,也停在入口,两者在入口相遇。

解题思路的配图

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

在阅读器中可以用目录和搜索、切换深色模式、练习这篇笔记中的面试题:打开《23. 链表中环的入口结点》