Given head, the head of a linked list, determine if the linked list has a cycle in it.
Return true if there is a cycle, false otherwise.
Example 1
Input: head = [3,2,0,-4], pos=1
Output: true
Explanation: Tail connects to node at index 1.
Example 2
Input: head = [1], pos=-1
Output: false
Explanation: No cycle.
The number of nodes is in the range [0, 10^4].Floyd's cycle detection: fast pointer moves 2 steps, slow moves 1 — they meet if there's a cycle.
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true; // they met — cycle exists
}
return false;
}Time: O(n) · Space: O(1)