List Cycle

 https://www.interviewbit.com/problems/list-cycle/


ListNode* Solution::detectCycle(ListNode* A) {
    //Floyd's cycle finding algorithm
    if(!A  || !A->next){
        return NULL;
    }
    ListNode* slow;
    ListNode* fast;
    slow=fast=A;
    while(fast){
        if(!fast->next || !fast->next->next){
            return NULL;
        }
        fast=fast->next->next;
        slow=slow->next;
        if(fast==slow) break;
    }
    slow=A;
    while(slow!=fast){
        slow=slow->next;
        fast=fast->next;
    }
    return slow;
}


Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!