Why my code gives this error "Last executed input: [], 1 " ?


  • 0
    K
    class Solution {
    public:
        ListNode* remove_beg(ListNode* head)
        {
            ListNode *nextptr=head;
            head=head->next;
            free(nextptr);
            return head;
        }
        ListNode* remove_end(ListNode* head)
        {
            ListNode *nextptr=head, *prevptr;
            while(nextptr->next != NULL)
            {
                prevptr=nextptr;
                nextptr=nextptr->next;
            }
            prevptr->next=NULL;
            free(nextptr);
            return head;
        }
        ListNode* removeElements(ListNode* head, int val) {
            ListNode *nextptr=head, *prevptr;
            if(nextptr->val == val && nextptr->next !=NULL)
            {
                head=remove_beg(head);
                return head;
            }
            else if(nextptr->val == val && nextptr->next == NULL)
            {
                head=remove_end(head);
                return head;
            }
            else
            {
                while(nextptr->val != val)
                {
                    prevptr=nextptr;
                    nextptr=nextptr->next;
                }
                prevptr->next=nextptr->next;
                free(nextptr);
                return head;
            }
        }
    };

  • 1

    Why my code gives this error "Last executed input: [], 1 " ?

    It doesn't. It gives "Runtime Error". The "Last executed ..." just tells you the last test case you were given. As you can see, it's the empty list. That is, head is a null pointer. Which you access right away without checking it, so of course you get an error.


  • 0
    K

    Thanks, but i tried to handle it by writing
    if(head == NULL)
    {
    return head;
    }
    else
    {
    //check for other cases in removeElements function
    }

    Now, the Runtime error got changed with " Last executed input: [1], 1 ". Am I not understanding it well? Please... , may be you have some another method to understand me... !!! Special Thanks to you...


  • 0

    Same kind of error. In remove_end you don't initialize prevptr and then you do prevptr->next=NULL;.

    Don't you get these errors when you run it on your PC?


Log in to reply
 

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