Recursive one-pass C++ solution

  • 0

    The helper() function is the part doing the recursion.

    class Solution {
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            return helper(NULL, head, n);
        ListNode* helper(ListNode* prev, ListNode* curr, int& n) {
            if (curr == NULL) return NULL;
            helper(curr, curr->next, n);
            if (n==0 && prev==NULL) {free(curr); return curr->next;}
            else if (n==0 && prev!=NULL) {free(curr); prev->next = curr->next;}
            return curr;

Log in to reply

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