Clear and easy understanding c++ code


  • 0
    S
    ListNode *detectCycle(ListNode *head) {
        if(!head) return NULL;
        ListNode *first=head, *second=head;
        while(second && second->next)
        {
            first=first->next;
            second=second->next->next;
            if(first==second) break;
        }
        if(!second || !second->next) return NULL;
        int cnt=1;
        first=first->next;
        while(first!=second) {
            cnt++;
            first=first->next;
        }
        
        ListNode *one=head, *two=head;
        while(cnt)
        {
            two=two->next;
            cnt--;
        }
        while(one!=two)
        {
            one=one->next;
            two=two->next;
        }
        return one;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.