TLE ? what should be the problem ? code is working for detect cycle


  • 0
    A

    class Solution {
    public:

    ListNode *detectCycle(ListNode *head) {
    
        ListNode *p=head,*q=head;
        bool pk=false;
        while(p!=NULL) 
        {
            p=p->next;
            
            
            if(p==q)
            {
               pk=true;
               break;
            }
            if(p==NULL)
            break;
            
            p=p->next;
            if(p==q)
            {
               pk=true;
               break;
            }
           
            q=q->next;
            
        }
        if(pk)
        {
            q=head;
            while(p!=q)
            {
                p=p->next;
                q=q->next;
            }
            return q;
        }
       
            return NULL;
    }
    

    };


  • 0
    V

    i think the error is here while(p!=q) p have a same speed one step with q,so q will not equal p in some special case.so it will be a forever circle


Log in to reply
 

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