解题思路


这题的思路可以说是建立在环形链表

在找到循环位置后,将slow回到head,然后查找 fast 和 slow 相遇的位置,这样就是环的入口了
详情参考:https://leetcode.cn/problems/linked-list-cycle-ii/solutions/12616/linked-list-cycle-ii-kuai-man-zhi-zhen-shuang-zhi-

实现代码


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

复杂度分析


  • 时间复杂度:O(N)
  • 空间复杂度:O(1)