[Runtime Error] Why my code is not correct?


  • 0
    N

    Submission Result: Runtime Error

    Last executed input: {1,2,3}, 1

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            if(head == NULL)  return NULL;
            
            ListNode *p1, *p2;
            p1 = head->next;
            p2 = head;
            
            int i = 0;
            while(p1 != NULL && p2 != NULL)
            {
                if(i++<n+1) 
                {
                    p2 = p2->next;
                } 
                else 
                {
                    p1 = p1->next;
                    p2 = p2->next;
                    
                    if (p2->next == NULL) 
                    {
                        ListNode *temp = p1->next;
                        p1->next = temp->next;
                        delete temp;
                        break;
                    }
                }
            }
            
            return head;
        }
    };

  • 0
    N

    I figured out the problem here. and the assumption is that this linked-list has no header node here. Actually, the parameter - "head" being passed in as the function's input is the pointer to the first data node of list, and it's not the header node which only has the pointer to the first real data node but no data field existing inside.

    Question: Does such kind of assumption is reasonable?


Log in to reply
 

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