Li Buckle 141_ ring chain watch

Determine whether the linked list has a ring

Using fast and slow pointers, similar to "tortoise and hare", suppose there is a ring in the watch, then the fast "rabbit" enters the ring first, then circles inside, and the "tortoise" enters the ring afterwards. They all circle in a ring , Because of the unequal speed, they will definitely meet.

public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while(slow != fast){
            if (slow == null || fast == null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

Why should the initial condition be set one after the other, then slow points to head and fast points to head.next?
Because the termination condition is slow equals fast, it is necessary to avoid the situation that the two are equal at the beginning.

Complexity analysis

Time complexity: O(n)
Space complexity: O(1)

Guess you like

Origin blog.csdn.net/Yungang_Young/article/details/112797017