#K6856. Cycle Detection in a Linked List
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:
- An integer
n
, representing the number of nodes in the linked list. - If
n > 0
, a line withn
space-separated integers representing each node's value. - An integer
pos
which is the 0-indexed position of the node that the tail connects to in order to form a cycle. Ifpos
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.
5
1 2 3 4 5
2
True