Back to DSA
Linked List Cycle
easyGiven the head of a singly linked list, determine whether the list contains a cycle. A cycle exists when following the links from some node eventually leads back to a previously visited node, forming a loop.
Examples
Example 1:
Input:
head = [5,8,2,-1], pos = 2Output:
true Example 2:
Input:
head = [4], pos = -1Output:
falseHints
class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}Time complexity
O(n)Space complexity
O(1)