Write a function to detect if a cycle exists in a linked list
HardProblem 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;
}
}
Input
Linked list with nodes pointing as follows: 1 → 2 → 3 → 4 → 2 (cycle)
Expected Output
true