Detect Cycle in Linked List
Mediumjavapythonccppjavascript
A singly linked list of N nodes (indices 0 .. N-1) is described. The tail's next pointer either points at the node with index pos, forming a cycle, or is null (given as pos = -1). Determine whether the list contains a cycle.
Input Format
The first line contains an integer N. The second line contains N space-separated integers, the node values (empty if N is 0). The third line contains an integer pos: the index the tail links back to, or -1 for no cycle.
Output Format
Print 1 if the list contains a cycle, otherwise print 0.
Example 1
Input
4 1 2 3 4 1
Output
1
Explanation: The tail links back to index 1, so following the links loops forever.
- 0 <= N <= 100000
- -1 <= pos <= N-1