C++ one pass solution, and remember to call free() to free memory.


  • 0
    E

    Hint:

    1. head = NULL
    2. n > link's node count
    3. memory leak
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode* p1 = head, *p2 = head;
            while (n-- > 0 && p1) {
                p1=p1->next;
            }
            if (n > 0 || p1 == NULL) {  
                if (!head) {
                    return NULL;
                } else {
                    // call free, or there'll be memory leak
                    ListNode* next = head->next;
                    free(head);
                    return next;
                }
            }
            while(p1->next) {
                p1=p1->next;
                p2=p2->next;
            }
            ListNode* next = p2->next;
            if (next) {
                p2->next = p2->next->next;
                free(next); // call free, or there'll be memory leak
            }
            return head;
        }
    };
    

Log in to reply
 

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