Cycle Detection

  • + 0 comments

    C++

    bool has_cycle(SinglyLinkedListNode* head) {
        unordered_set<SinglyLinkedListNode*> address; // a set of SLL num_set
        
        // for every node until the end of the SLL    
        while (head){        
            if (address.find(head) != address.end()) // if found the head in address
                return 1; // return 1 and terminate
            else 
                address.insert(head); // if did not find the head in address, then insert head as another element in address
                
            head = head->next; // move to the next node in the SLL
        }
        return 0; // if we got here then return zero
    }