let 142. Linked List Cycle II

首先如何找链表有环
解法:
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode first=head;
ListNode second=head;
while(second.next!=null&&second.next.next!=null){

        first=first.next;
        second=second.next.next;
        if(first==second) return true;
    }
    return false;
}

}


现在提升,难度,找到环开始的地方,

根据如下规则,
假设环开始的i地方是头接点走A 步, 当发现环时 第一个慢节点总共走了A+B步,那么快节点走了2A+2B步, 快节点比慢节点夺走了一个环的长度,环的长度为N
N=A+B
当头接点走A步的时候,慢节点再走A步, A+B+B=N+A,慢节点就是走A+一个环的距离,此时慢节点和头接点正好相等。所以可以确认环开始的位置。

AC 代码如下:


public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null) return null;
        if(head.next==head) return head;
        ListNode first=head;
        ListNode second=head;

        while(second.next!=null&&second.next.next!=null){
            first=first.next;
            second=second.next.next;
            if(first==second){

                ListNode start=head;
                while(start!=first){
                    start=start.next;
                    first=first.next;
                }
                return start;
            }
        }

      return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值