Easy thinking solution


  • 0
    J
    public:
        ListNode *detectCycle(ListNode *head) {
            if(head==NULL||head->next==NULL)
                return NULL;
            ListNode* slow=head,*fast=head;
            do{
                slow=slow==NULL?NULL:slow->next;
                fast=fast==NULL?NULL:(fast->next==NULL?NULL:fast->next->next);
            }while(slow!=NULL&&fast!=NULL&&slow!=fast);
            if(slow==NULL||fast==NULL)
                return NULL;
            slow=head;
            while(slow!=fast)
            {
                slow=slow->next;
                fast=fast->next;
            }
            return slow;
        }
    };
    

Log in to reply
 

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