My simple solution but hit a corner case


  • 0
    L

    Here is my code below:

    ListNode *detectCycle(ListNode *head) {
            ListNode *s = head, *f = head;
            ListNode *pre;
            while (f && f->next) {
                pre = s;
                s = s->next;
                f = f->next->next;
                if (s == f) { // there is a cycle
                    while (s) {
                        pre->next = NULL; // to break the cycle
                        pre = s;
                        s = s->next;
                    }
                    s = head;
                    while (s) {  // find the start point 
                        if (s->next) s = s->next;
                        else return s;
                    }
                }
            }
            
            return NULL;
        }
    

    However, I hit the error:
    Input: {-1,-7,7,-4,19,6,-9,-5,-2,-5}, tail connects to node index 9
    Output: tail connects to node index 8
    Expected: tail connects to node index 9

    It is confusing that the last cycle is : -5 --> -2 --> -5 and why it says the expected tail connects to node index 9. -5 should be the start point of the cycle, right? The index is from 0 or 1?


Log in to reply
 

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