Dare2Solve
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.
Initialization:
head
is null or if the list contains only one node (head.next
is null). In either case, return false
because a cycle is not possible.Pointer Setup:
slow
and fast
. Both start at the head of the list.slow
moves one step at a time.fast
moves two steps at a time.Traversal:
slow
one step forward.fast
two steps forward.slow
and fast
meet at any point, return true
because a cycle exists.fast
or fast.next
becomes null, return false
because it indicates the end of the list and no cycle is present.Return:
false
as no cycle was detected./**
* 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;
}
};
# 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
/**
* 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;
}
}
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;
};