LeetCode——linked-list-cycle-ii(找出链表中环的入口节点)

知识点:链表
[原文地址](https://github.com/DmrfCoder/AlgorithmAndDataStructure/blob/master/LeetCode/Doc/找出链表中环的入口节点.md)

题目描述

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

给定一个链表,返回其中环的入口节点,如果没有环,返回null
提示:尽量不要使用额外空间。

解题思路

参考:https://www.nowcoder.com/questionTerminal/6e630519bf86480296d0f1c868d425ad

思路:

1)使用快慢指针方法,判定是否存在环,并记录两指针相遇位置(Z);

2)将两指针分别放在链表头(X)和相遇位置(Z),并改为相同速度推进,则两指针在环开始位置相遇(Y)。

证明如下:

如下图所示,X,Y,Z分别为链表起始位置,环开始位置和两指针相遇位置,则根据快指针速度为慢指针速度的两倍,当两指针相遇时快指针一定比慢指针多走了n圈,可以得出:

2 ∗ ( a b ) = a b n ∗ ( b c ) 2*(a b) = a b n * (b c) 2(a b)=a b n(b c)

a = ( n − 1 ) ∗ b n ∗ c = ( n − 1 ) ( b c ) c ​ a=(n - 1) * b n * c = (n - 1)(b c) c​ a=(n1)b nc=(n1)(b c) c;

LeetCode——linked-list-cycle-ii(找出链表中环的入口节点)_第1张图片

注意到b c恰好为环的长度,这时如果可以再让快指针走c步(只要是整数圈多c部即可)即可找出入口点了,所以我们再用两个指针,第一个指针p1指向起点X,第二个指针p2指向刚才相遇的点Z,然后让p1和p2一次走一步,当p1走了a步也就是 ( n − 1 ) ( b c ) c (n - 1)(b c) c (n1)(b c) c步时,p2也走了 ( n − 1 ) ( b c ) c (n - 1)(b c) c (n1)(b c) c步,注意p2起点距离圆的入口点多了b步,那么此时p2应该相对于圆的入口点走了 ( n − 1 ) ( b c ) c b = n ( b c ) (n-1)(b c) c b=n(b c) (n1)(b c) c b=n(b c)步,也就是到了圆的入口点,而p1走了a步自然也到了圆的入口点,所以此时p1与p2会相遇,那么反向推倒,当p1与p2相遇时刚好就在圆的入口点。

代码

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

        if (fast.next == null || fast.next.next == null) {
            return null;
        }

        fast = head;
        while (fast != null && slow != null) {
            if (fast == slow) {
                return fast;
            }
            fast = fast.next;
            slow = slow.next;

        }
        return null;


    }

完整代码

你可能感兴趣的:(LeetCode,算法与数据结构)