🎨Now live: Try our Free AI Image Generation Feature

Intuition
To detect a cycle in a linked list, we can use two pointers that traverse the list at different speeds. If there is a cycle, the faster-moving pointer will eventually meet the slower-moving pointer. This method leverages the concept of a "tortoise and hare" race, where the hare (fast pointer) moves two steps at a time and the tortoise (slow pointer) moves one step at a time.
Approach
- Initialization:
- Check if the
head
is null or if the list contains only one node (head.next
is null). In either case, returnfalse
because a cycle is not possible. - Pointer Setup:
- Initialize two pointers,
slow
andfast
. Both start at the head of the list. -slow
moves one step at a time. -fast
moves two steps at a time. - Traversal:
- Iterate through the list:
- In each iteration, move
slow
one step forward. - Movefast
two steps forward. - Ifslow
andfast
meet at any point, returntrue
because a cycle exists. - Iffast
orfast.next
becomes null, returnfalse
because it indicates the end of the list and no cycle is present. - Return:
- If the loop exits, return
false
as no cycle was detected.
Complexity
Time Complexity:
- The time complexity is O(n), where n is the number of nodes in the list. In the worst case, both pointers traverse the entire list once.
Space Complexity:
- The space complexity is O(1) because only a constant amount of extra space is used for the two pointers.
Code
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head || !head->next) {
return false;
}
ListNode *slow = head;
ListNode *fast = head->next;
while (slow != fast) {
if (!fast || !fast->next) {
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head or not head.next:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
Java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
JavaScript
var hasCycle = function(head)
{
if (!head || !head.next) {
return false;
}
let slow = head;
let fast = head.next;
while (slow !== fast) {
if (!fast || !fast.next) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
};