#C5873. Circular Linked List Detection
Circular Linked List Detection
Circular Linked List Detection
You are given a linked list and your task is to determine whether it is circular. A linked list is considered circular if its last node points back to the first node. In other words, if the first and last node share the same value (for non-empty lists), then the list should be considered circular. Note that:
- An empty list is not circular.
- A single-node list is always circular because the only node points to itself.
- For lists with more than one node, if the value of the first node is equal to the value of the last node, then assume that the last node has been linked back to the first node, making the list circular.
You are required to read input from standard input (stdin
) and output the result to standard output (stdout
). Use appropriate techniques (such as Floyd’s Tortoise and Hare algorithm) to detect a cycle in the linked list.
Note: The input format is designed to contain multiple test cases. Make sure your solution processes all test cases correctly.
inputFormat
The input begins with an integer T
(1 ≤ T ≤ 100), the number of test cases. For each test case:
- An integer
n
(n ≥ 0) representing the number of nodes. - If
n > 0
, a line follows containingn
space-separated integers representing the node values.
Note:
- If
n = 0
, then the list is empty. - For a non-empty list with
n > 1
, if the first and the last node values are equal, the list is to be treated as circular. - For a single-node list (
n = 1
), it is considered circular by definition.
outputFormat
For each test case, print a single line containing either YES
if the linked list is circular, or NO
if it is not.
5
5
1 2 3 4 5
3
7 8 7
0
1
1
1
2
NO
YES
NO
YES
YES
</p>