#141
Easy Algorithms Linked list cycle
Hash Table Linked List Two Pointers
53.9% acceptance
Jan 13, 2026
17412
1574
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 in the linked list. Otherwise, return false.
Solution
C++
Time O(n)
Space O(1)
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};