腾讯五十题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 @ 2022-02-08 17:12  蹇爱黄  阅读(46)  评论(0)    收藏  举报