A 4ms C++ Solution


  • 0
    Y
    /**
     * 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) {
            int count = 1;
            ListNode* curr = head;
            while(curr->next != NULL) {
                count++;
                curr = curr->next;
            }
            curr = head;
            if(count != n) {
                for(int i = 0; i < count - n - 1; i++) {
                    curr = curr->next;
                }
                curr->next = curr->next->next;
                return head;
            } else return head->next;
        }
    };

  • 0
    F

    Isn't this a two pass solution?


Log in to reply
 

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