142. Linked List Cycle II

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

在这里插入图片描述
判断有没有环,如果没有环,返回null
如果发现快慢指针相等了,则说明有环,然后将快指针放到head,慢指针从相遇处,各自一步一步走,再次相遇就是环的入口。
在这里插入图片描述
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c
在这里插入图片描述
精确分析:
第一个慢指针走过的路程长度是x1 + x2 + k1 * (x2 + x3)。
第二个快指针走过的路程长度是x1 + x2 + k2 * (x2 + x3)。
由快慢指针的速度关系得:(x1 + x2) * 2 + 2 * k1 * (x2 + x3) = x1 + x2 + k2 * (x2 + x3),因此x1 + x2 = (k2 - 2 * k1) * (x2 + x3),进而有x1 - x3 = (k2 - 2 * k1 - 1) * (x2 + x3)。
这说明x1和x3的距离差值刚好是环长(x2 + x3)的整数倍。 因此,我们只需令其中一个指针指向虚拟头节点,而另一个指针则仍然在相遇的那个节点,一起移动这两个指针,直到这两个指针相遇,这个新的相遇点就是链表开始入环的第一个节点。

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (fast == slow) {
            // 找到环以后,fast放到head,然后再走,再相遇,相遇的节点就是入口
                fast = head;
                while (fast != slow) {
                    fast = fast.next;
                    slow = slow.next;
                }
                return fast;
            }
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值