Simple c++ solution, 6ms, 3 points


  • 0
    C
    /**
     * 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) {
            ListNode *pre, *rm, *last;
            pre = rm = last = head;
            for (int i = 0; i < n - 1; ++i) {
                last = last->next;
            }
            if (last->next == NULL) 
                return head->next;
            rm = rm->next;
            last = last->next;
            while (last->next != NULL) {
                last = last->next;
                rm = rm->next;
                pre = pre->next;
            }
            pre->next = rm->next;
            
            return head;
        }
    };
    

Log in to reply
 

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