Tortoise and hare implementation C++


  • 0
    L

    My logic is to initialize the slow and fast pointers with the head of the link list and it will exit out of the while condition if there is no cycle.


    class Solution {
    public:
    bool hasCycle(ListNode *head) {
    ListNode *slow = head;
    ListNode *fast = head;
    while(slow and fast and fast->next) {
    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.