To detect a cycle in a linked list, we use the Floyd's Tortoise and Hare algorithm.
This involves two pointers: a
slow pointer
that moves
one step
at a time and
a
fast pointer
that moves
two steps
at a time. If
there is a cycle, the
fast pointer
will
eventually
meet
the
slow
pointer
. If the fast pointer reaches the
end of the list (NULL),
it means there is no cycle.
/** * 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) { ListNode *slow = head; ListNode *fast = head; while(fast!=NULL && fast->next != NULL){ slow = slow->next; fast = fast->next->next; if(fast==slow) return true; } return false; } };
The algorithm iterates through the linked list once, making it linear in time complexity.
The algorithm uses only two pointers, ensuring constant space usage.