力扣142.环形链表II (链表)

image

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
        //根据Floyd判圈法算出入口节点位置
                while (slow != head) {
                    slow = slow.next;
                    head = head.next;
                }
                return slow;
            }
        }
        return null;
    }
}
posted @ 2026-01-14 10:53  Huangyien  阅读(3)  评论(0)    收藏  举报