Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-11-03 01:32:02
Original
372 people have browsed it

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:

<code class="java">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.
        }
    }
}</code>
Copy after login

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

The above is the detailed content of How Does Floyd\'s Algorithm Detect Loops in Linked Lists?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!