腾讯五十题No.31 环形链表II

题目链接

判断环的入口,需要先判断有没有环,在寻找环的入口,找入口时需要重新定义两个”指针“,一个指向头节点,一个指向当前fast,让他们前进速度相同,他们想入的点即为入口。

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head,slow = head;
        while(fast!=null && fast.next!=null){
            fast = fast.next.next;
            slow = slow.next;
            //判断是否有环
            if(fast==slow){
                ListNode index1 = fast;
                ListNode index2 = head;
                //查找环入口
                while(index1!=index2){
                    index1 = index1.next;
                    index2 = index2.next;
                }
                return index1;
            }
        }
        return null;
    }
}

posted @   蹇爱黄  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示