#K9531. Detect Cycle in a Linked List

    ID: 38835 Type: Default 1000ms 256MiB

Detect Cycle in a Linked List

Detect Cycle in a Linked List

Given a linked list, your task is to determine whether the list contains a cycle. A cycle occurs when a node's next pointer points to a previous node in the list, forming a loop.

The linked list is represented in the input as follows:

  • The first line contains an integer n which indicates the number of nodes in the linked list.
  • The second line contains n integers, representing the value of each node.
  • The third line contains a single integer pos. This represents the 0-indexed position of the node that the last node's next pointer is connected to, forming a cycle. If pos is -1, then there is no cycle in the list.

Note: You are required to implement a cycle detection algorithm in which the typical approach is using two pointers (slow and fast). The pointers move through the list at different speeds, and if they ever meet, a cycle exists. In terms of mathematics, if there is a cycle, then eventually the following condition will be met:

[ \text{if } slow == fast \text{ then there is a cycle}. ]

Output True if a cycle is detected, or False otherwise.

inputFormat

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

  1. An integer n (number of nodes in the linked list).
  2. n space-separated integers representing the node values.
  3. An integer pos indicating the 0-indexed position where the tail connects. A value of -1 means no cycle exists.

outputFormat

Output to standard output (stdout) a single line containing either True if the linked list has a cycle, or False if it does not.

## sample
1
1
-1
False