detectAndRemoveLoop<T> function

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

Implementation

bool detectAndRemoveLoop<T>(LinkedListNode<T>? head) {
  if (head == null) return false;
  LinkedListNode<T>? slow = head, fast = head;
  // Detect loop
  while (fast != null && fast.next != null) {
    slow = slow!.next;
    fast = fast.next!.next;
    if (slow == fast) break;
  }
  if (fast == null || fast.next == null) return false;
  // Find loop start
  slow = head;
  while (slow != fast) {
    slow = slow!.next;
    fast = fast!.next;
  }
  // Remove loop
  while (fast!.next != slow) {
    fast = fast.next;
  }
  fast.next = null;
  return true;
}