Practice Real Company Assessment Patterns • Latest 2025–2026 Mock Tests

Programming Exercises

Write a function to detect if a cycle exists in a linked list

Hard

Problem Statement

Write a function to detect if a cycle exists in a linked list

Sample Input

Linked list with nodes pointing as follows: 1 → 2 → 3 → 4 → 2 (cycle)

Sample Output

true

Limits

Time: 2s · Memory: 256 MB

Code Editor
00:00
import java.util.*; class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class Main { public static boolean hasCycle() { // Create the linked list with a cycle here // Your code here return false; } }
Log in or sign up to run or submit your code.Log inSign up
Input
Linked list with nodes pointing as follows: 1 → 2 → 3 → 4 → 2 (cycle)
Expected Output
true