#C5410. Cycle Detection in a Linked List
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:
- An integer \(n\) representing the number of nodes in the linked list.
- \(n\) space-separated integers representing the values of the nodes.
- 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.
4
3 2 0 -4
1
True