141. Linked List Cycle - cocoder39/coco39_LC GitHub Wiki
if there is cycle, the distance between fast
and slow
would decrease by one each time, there is a moment when fast
catches up slow
compared with fast and slow pointers in 234. Palindrome Linked List, here we do not care about while (fast && fast->next)
or while (fast->next && fast->next->next)
, we just need ensure the pointer is valid when accessing its next pointer
bool hasCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}