142. Linked List Cycle II leetcode java

题目:

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

Note: Do not modify the linked list.

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

思路:

方法是利用两个指针从头开始,指针slow一次走一步,指针fast一次走两步,如果有环则两指针必定有重逢之时(这是Linked List Cycle里用到的)。

然后就是如何求出环的起始节点。

可以这么假定,从链的起点到环的起点,这段距离称为a。环的长度称为c,第一次相遇位置距环的起点距离为p。首先slow被fast追上时它一定没有走完整个环(想想为什么?)也就是说0<p<c.所以从出发到相遇,slow走过的距离为a+p,fast走过的距离为a+p+nc(n为正整数)。又因为p2速度为p1两倍,所以有2a+2p=a+p+nc,所以有a+p=nc。现在两指针均处在环起点过p的位置上,再走a个距离即可回到环的起点。而a恰好是链的起点到环的起点的距离,所以我们另其中一指针回到链的起点,另一指针仍在原地,同时以速度1前进,再次相遇一定是在环的起点了。

算法:

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

参考:https://blog.youkuaiyun.com/monkeyduck/article/details/40083527

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值