What is the problem in following code? Last executed input:[] no cycle


  • 0
    M
    bool hasCycle(struct ListNode *head) {
        struct ListNode *sp,*fp;
        sp=head->next;
        fp=sp->next;
        while(fp->next)
        {
            sp=sp->next;
            fp=fp->next->next;
            if(sp==fp)
            {
                return 1;
            }
        }
        return 0;
    }
    

    Please help me solve this problem.


  • 0
    Z
    This post is deleted!

  • 0
    K

    Is the error NullPointerException?
    If it is, it is due to the following reason:
    in your code, you wrote fp-> next, then fp = fp->next->next
    suppose the list has no cycle, fp will be null at last,
    in the next loop you check fp->next, since fp now is null, it is invalid to write fp->next.
    I have the same error at first,
    change the while condition to (java version) while(fp != null && fp.next != null) and I think at least the error can be solved.


  • 0
    I

    I agree with King_YL


Log in to reply
 

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