#K9531. Detect Cycle in a Linked List
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:
- An integer
n
(number of nodes in the linked list). n
space-separated integers representing the node values.- 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.
1
1
-1
False