Monday 17 October 2016

Linked Lists: Detect a Cycle (CTCI)

Problem: Linked Lists: Detect a Cycle

bool has_cycle(Node* head) {
    if(head==NULL) return 0;
    Node *slow=head, *fast=head;
    
    while(fast!=NULL && fast->next!=NULL)
    {
        slow=slow->next;
        fast=fast->next->next;
        if(slow==fast) return 1;
    }
    return 0;
}

2 comments: