My Solution is much like @stackpop,but I get a TLE. Could Anybody tell me why


  • 0
    J
    class Solution {
    

    public:
    ListNode *detectCycle(ListNode *head) {
    if (head==NULL)
    {
    return NULL;
    }

        ListNode *pSingleSpeed=head;
        ListNode *pDpubleSpeed=head;
    
        while (pSingleSpeed!=NULL&&pDpubleSpeed!=NULL)
        {
            pSingleSpeed=pSingleSpeed->next;
            pDpubleSpeed=pDpubleSpeed->next;
            if (pDpubleSpeed!=NULL)
            {
                pDpubleSpeed=pDpubleSpeed->next;
            }
            /*  else
            {
            return NULL;
            }*/
            if (pSingleSpeed==pDpubleSpeed/*&&pSingleSpeed!=NULL
                &&pDpubleSpeed!=NULL*/)
            {
                break;
            }
        }
       
        if (pDpubleSpeed==NULL||pSingleSpeed==NULL)
        {
            return NULL;
        }
        
        pDpubleSpeed=head;
        while (pDpubleSpeed!=pSingleSpeed)
        {
            pSingleSpeed=pDpubleSpeed->next;
            pSingleSpeed=pSingleSpeed->next;
        }
        return pSingleSpeed;
    }
    

    };


Log in to reply
 

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