Dsa
Linked List
Medium
Find the Cycle in a Linked List
You are given a linked list. Your task is to determine whether there is a cycle in the linked list. A cycle exists if any node is reachable again by continuously following the next pointers. Implement a program that reads the linked list and checks for a cycle. It should print 'YES' if there is a cycle, and 'NO' otherwise. The input format will include a series of integers for the node values and an additional integer indicating the position (-1 means no cycle).
Input Format:
- The first line contains a series of integers that represent the linked list nodes.
- The second line contains an integer indicating the position of the node to connect to (0-indexed) or -1 for no cycle.
Output Format:
- Print 'YES' if there is a cycle, otherwise print 'NO'.
Example:
Input:
3 2 0 4 5 -1
2
Output:
YES
Key concepts
linked_listcycle_detectiontwo_pointers
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now