4 ms C solution


  • 0

    struct ListNode *detectCycle(struct ListNode *head) {

    if( !head || head -> next == NULL )
        return NULL;
    struct ListNode *slow = head, *fast = head;
    while( fast && fast -> next ) {
        slow = slow -> next;
        fast = fast -> next -> next;
        if( slow == fast )
            break;
    }
    if( fast != slow )
        return NULL;
    while( head != slow ) {
        slow = slow -> next;
        head = head -> next;
    }
    return head;
    

    }


Log in to reply
 

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