Leetcode # 141. Linked List Cycle
- 2022.12.05
- Floyd's tortoise and hare LeetCode Linked List
https://leetcode.com/problems/linked-list-cycle/
Solution
Time Complexity: O(len(linked_list))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *hare = head, *tortorise = head;
while(hare != NULL && tortorise != NULL){
hare = hare->next;
if(hare != NULL)hare = hare->next;
tortorise = tortorise->next;
if(hare == tortorise)break;
}
return hare != NULL;
}
};
Last Updated on 2023/08/16 by A1go