C++ Solution using classic two pointers


  • 0
    Y

    If there is a loop, slow and fast pointers will meet. Saw this solution in the book cracking the coding interviews. It's a FAQ.

    class Solution {
    public:
    bool hasCycle(ListNode *head) {

        if (head == NULL || head->next == NULL) {
            return false;
        }
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast->next != NULL && fast->next->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.