C++ solution that uses 2 traversals


  • 0
    K
    /**
     * 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) {
            if(head == NULL) return head;
            ListNode* temp = head;
            int i;
            for(i = 0; temp != NULL; temp = temp->next) i++;
            
            temp = head;
            if(i == 1 && n == 1) return NULL;
            if(i == n) {
                temp = head;
                head = head->next;
                delete temp;
                return head;
            }
            else
            {
                for(int j = 0; j < i - n - 1; j++){
                    temp = temp->next;
                }
                ListNode* toDelete = temp->next;
                temp->next = toDelete->next;
                delete toDelete;
            }
            return head;
        }
    };

Log in to reply
 

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