LC 19. Remove Nth Node From End of List

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
private:
    int countNode(ListNode *head){
        ListNode* temp = head;
        int n = 0;
        while(temp){
            n++;
            temp = temp->next;
        }
        return n;
    }
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int p = countNode(head);
        if(n==p){
            head = head->next;
            return head;
        }
        ListNode* temp = head;
        while(temp && p!=n+1){
            p--;
            temp = temp->next;
        }
        temp->next = temp->next->next;
        return head;
    }
};


Dicussion Forum