c++ solution in 3ms


  • 0
    K

    '''
    ListNode* removeNthFromEnd(ListNode* head, int n) {
    ListNode dummy(-1);
    dummy.next=head;
    ListNode *pre = &dummy,*fast_p=&dummy,*slow_p=&dummy;
    while(n--) fast_p=fast_p->next;
    while(fast_p->next)
    {
    fast_p=fast_p->next;
    slow_p=slow_p->next;
    }
    slow_p->next=slow_p->next->next;
    return pre->next;
    }
    '''


  • 0
    K

    Set two pointers, one is fast, the other is slow. The fast pointer goes first. When fast pointer goes to the Nth node, slow pointer starts to go. Delete the node pointed by the slow pointer when the fast pointer reach the end of the list.


Log in to reply
 

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