detectCycle<T> function

bool detectCycle<T>(
  1. LinkedListNode<T>? head
)

Detects if a cycle exists in the linked list using Floyd's algorithm

head - The head of the linked list to check Returns true if a cycle exists, false otherwise

Time Complexity: O(n) where n is the length of the list Space Complexity: O(1)

Implementation

bool detectCycle<T>(LinkedListNode<T>? head) {
  if (head == null || head.next == null) return false;

  LinkedListNode<T>? slow = head; // Tortoise
  LinkedListNode<T>? fast = head; // Hare

  // Move slow by 1 and fast by 2
  while (fast != null && fast.next != null) {
    slow = slow!.next;
    fast = fast.next!.next;

    // If they meet, there's a cycle
    if (slow == fast) {
      return true;
    }
  }

  return false;
}