Clean C++ two pointers


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

Log in to reply
 

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