Linked Lists: Detect a Cycle

  • + 0 comments

    C++

    bool has_cycle(Node* head) {
        // Complete this function
        // Do not write the main method
        
        Node* slowerPtr = head;
        Node* fasterPtr = head;
        
        if ( (head == nullptr) || (head->next == nullptr) ){
            return false;   
        }
        
        while( (fasterPtr != nullptr) && (fasterPtr->next != nullptr) ){
            slowerPtr = slowerPtr->next;
            fasterPtr = fasterPtr->next->next;
            if (slowerPtr == fasterPtr){
                return true;
            }
        }
        return false;
    }