public class Solution {
// Function to find the length of the cycle
public static int findLength(Node slow, Node fast)
{
int count = 1; // Initialize count to 1 as we're already in the cycle fast = fast.next; // Move fast pointer once
// Loop until slow and fast pointers meet again
while (slow != fast)
{
count++; // Increment count
fast = fast.next; // Move fast pointer
}
return count; // Return the length of the cycle
}
// Function to find the length of the cycle in the linked list
public static int lengthOfLoop(Node head)
{
Node slow = head; // Initialize slow pointer
Node fast = head; // Initialize fast pointer
// Traverse the list to detect a cycle
while (fast != null && fast.next != null) {
slow = slow.next; // Move slow pointer by one step
fast = fast.next.next; // Move fast pointer by two steps // If slow and fast pointers meet, it indicates a cycle if (slow == fast) {
return findLength(slow, fast); // Return the length of the cycle }
} return 0; // If no cycle is found, return 0
}
}