"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Does Floyd\'s Algorithm Detect Loops in Linked Lists?

How Does Floyd\'s Algorithm Detect Loops in Linked Lists?

Published on 2024-11-07
Browse:820

How Does Floyd\'s Algorithm Detect Loops in Linked Lists?

Detecting Loops in Linked Lists Using Floyd's Algorithm

Determining whether a given linked list contains a loop can be a challenging task in Java programming. A loop occurs when the final node in the list refers to a previous node instead of having a null reference.

To detect loops efficiently, developers often employ Floyd's cycle-finding algorithm, also known as the tortoise and hare algorithm. This algorithm uses two references, a slow and a fast one, which traverse the list at different speeds.

For example, the slow reference advances by one node while the fast reference advances by two nodes. If the linked list contains a loop, these references will eventually meet. On the other hand, if there is no loop, either the slow or fast reference (or their subsequent references) will become null before the other reaches the end of the list.

Here is a Java implementation of Floyd's algorithm:

boolean hasLoop(Node first) {
    if (first == null) {
        return false; // List does not exist, so no loop
    }

    Node slow, fast; // Create two references.
    slow = fast = first; // Make both refer to the start of the list.

    while (true) {
        slow = slow.next; // One hop.

        if (fast.next != null) {
            fast = fast.next.next; // Two hops.
        } else {
            return false; // No loop.
        }

        if (slow == null || fast == null) {
            return false; // No loop.
        }

        if (slow == fast) {
            return true; // Loop detected.
        }
    }
}

This algorithm takes O(1) space complexity and runs in O(n) time, making it both memory-efficient and reasonably time-consuming.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3