package java_programs;
import java.util.*;

/**
 * This class provides a method to detect a cycle in a linked list using Floyd's Tortoise and Hare algorithm.
 * It involves using two pointers moving at different speeds to determine if a cycle exists.
 */
public class DetectCycle {

    /**
     * Detects if a cycle exists in a linked list.
     * @param head The head node of the linked list.
     * @return true if there is a cycle, false otherwise.
     */
    public static boolean detectCycle(Node head) {
        if (head == null) return false; // Early return if the list is empty

        Node slow = head; // Slow pointer moves one step at a time
        Node fast = head; // Fast pointer moves two steps at a time

        while (true) {
            if (fast == null || fast.getSuccessor() == null) {
                return false; // Fast pointer reached the end, no cycle
            }
            
            slow = slow.getSuccessor(); // Move slow pointer by one step
            fast = fast.getSuccessor().getSuccessor(); // Move fast pointer by two steps
            
            if (slow == fast) {
                return true; // Pointers met, cycle detected
            }
        }
    }
}