getCycleLength<T> function
Calculates the length of the cycle if it exists
head - The head of the linked list
Returns the length of the cycle, or 0 if no cycle exists
Time Complexity: O(n) where n is the length of the list Space Complexity: O(1)
Implementation
int getCycleLength<T>(LinkedListNode<T>? head) {
if (head == null || head.next == null) return 0;
LinkedListNode<T>? slow = head;
LinkedListNode<T>? fast = head;
// First phase: find the meeting point
bool hasCycle = false;
while (fast != null && fast.next != null) {
slow = slow!.next;
fast = fast.next!.next;
if (slow == fast) {
hasCycle = true;
break;
}
}
// If no cycle, return 0
if (!hasCycle) return 0;
// Second phase: count the length of the cycle
int length = 1;
fast = fast!.next;
while (slow != fast) {
fast = fast!.next;
length++;
}
return length;
}