Floyd's "tortoise and hare" algorithm


  • 0
    B

    While most have implemented the classic algorithm, no one referenced it. So here it goes: https://en.wikipedia.org/wiki/Cycle_detection

        bool hasCycle(ListNode *head) {
            ListNode* slow=head, *fast=head;
            while (fast!=NULL && fast->next!=NULL)
            {
                slow = slow->next;
                fast = fast->next->next;
                if (slow==fast) return true;
            }
            return false;
            
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.