#C5410. Cycle Detection in a Linked List

    ID: 49057 Type: Default 1000ms 256MiB

Cycle Detection in a Linked List

Cycle Detection in a Linked List

Given a singly linked list, determine whether it contains a cycle. A cycle occurs when a node's next pointer points back to a previous node in the list, forming a loop. Using Floyd's Tortoise and Hare algorithm, you must detect if such a cycle exists.

The linked list is defined as \(\texttt{ListNode}\) where each node contains an integer value and a pointer to the next node.

inputFormat

The input is read from stdin and consists of three lines:

  1. An integer \(n\) representing the number of nodes in the linked list.
  2. \(n\) space-separated integers representing the values of the nodes.
  3. An integer \(pos\) representing the 0-indexed position where the tail connects to form a cycle. If \(pos = -1\), then there is no cycle in the list.

outputFormat

Print True if the linked list contains a cycle; otherwise, print False. The output is written to stdout.

## sample
4
3 2 0 -4
1
True