Help! My solution got runtime error. (Remove Nth Node From End of List )


  • 0
    T

    Could anyone help me find the problem of my code? I couldn't think of where might go wrong. Thanks!

    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode* p = head;
            ListNode* q = head;
            for(int i = 0 ; i < n ; i++){
                q = q->next;
            }
            while(q->next != NULL){
                p = p->next;
                q = q->next;
            }
            ListNode* tmp = p->next;
            p->next = p->next->next;
            delete tmp;
            return head;
        }
    };

  • 0

    What if n equals the length of the list,which means you have to delete the head? Then after the "for" sentences, p is head and q is NULL, so you have to delete head instead of deleting tmp = p->next.
    So I add a judgement after the for-sentences and now it gets accepted.

    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* p = head;
        ListNode* q = head;
        for(int i = 0 ; i < n ; i++){
            q = q->next;
        }
        if(q == NULL) // if n == length of the list
        {
            ListNode* tmp = head->next;
            delete head;
            return tmp;
        }
        while(q->next != NULL){
            p = p->next;
            q = q->next;
        }
        ListNode* tmp = p->next;
        p->next = p->next->next;
        delete tmp;
        return head;
    }

Log in to reply
 

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