My C++ solution in 3ms


  • 0
    M

    ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode* before, after;
    before = after = head;
    for(int i = 0; i < n-1; ++i)
    {
    after = after->next;
    if(!after)
    return head;
    }
    ListNode
    prev = NULL;
    while(after->next != NULL)
    {
    prev = before;
    before = before->next;
    after = after->next;
    }
    ListNode* newHead = head;
    if(prev)
    prev->next = before->next;
    else
    newHead = head->next;
    delete before;
    before = NULL;

        return newHead;
    }

Log in to reply
 

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