#K6856. Cycle Detection in a Linked List

    ID: 32891 Type: Default 1000ms 256MiB

Cycle Detection in a Linked List

Cycle Detection in a Linked List

In this problem, you are given a singly linked list and you need to determine whether it contains a cycle. A cycle in the linked list occurs when a node's next pointer points back to a previous node, forming a loop. Use the Floyd's Tortoise and Hare algorithm to detect the cycle in \(O(n)\) time.

The input is provided through standard input and consists of the number of nodes, the node values, and the position where the tail connects to form a cycle. A position of -1 indicates that there is no cycle.

inputFormat

The input consists of three parts provided via stdin:

  1. An integer n, representing the number of nodes in the linked list.
  2. If n > 0, a line with n space-separated integers representing each node's value.
  3. An integer pos which is the 0-indexed position of the node that the tail connects to in order to form a cycle. If pos is -1, then there is no cycle.

outputFormat

Output a single boolean value to stdout: True if the linked list contains a cycle, and False otherwise.

## sample
5
1 2 3 4 5
2
True