Clean and easy to understand C solution


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

Log in to reply
 

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