C++, Two pointers

  • 0

    Two pointers, keep slowing running until the end, if faster reaches the end first, there is no circle. While, if it catches the slow pointer, there is a cycle.

        bool hasCycle(ListNode* head){
                return false;
            ListNode* slow = head;
            ListNode* fast = head->next;
                if(!fast || !fast->next)
                    return false;
                if(slow == fast)
                    return true;
                fast = fast->next->next;
                slow = slow->next;
            return false;

Log in to reply

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