栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode141-环形链表-------剑指Offer022-链表中环的入口

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode141-环形链表-------剑指Offer022-链表中环的入口

题目描述:LeetCode141-环形链表

思路:

采用快慢指针,fast和slow都从head开始出发,slow每次走一步,fast每次走两步,如果存在环,则一定会相遇。

代码:
public class Solution {
    public boolean hasCycle(ListNode head) {
        
        ListNode fast=head;
        ListNode slow=head;

        while(fast!=null && fast.next!=null){
            
            fast=fast.next.next;
            slow=slow.next;

            if(fast==slow){
                return true;
            }

        }
        return false;

    }
}
题目描述:剑指Offer022-链表中环的入口


如果链表为空返回null。

思路:

先通过快慢指针判断是否有环,存在环,则使fast回到头节点,slow留在相遇点,则当速度一致时,再次相遇点就是环的入口,返回即可。

代码:
public class Solution {
    public ListNode detectCycle(ListNode head) {
        
        if(head==null || head.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){
                break;
            }
        }

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

        fast=head;

        while(fast!=slow){
            fast=fast.next;
            slow=slow.next;
        }

        return fast;

    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/767732.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号