0ms recursive solution


  • 0
    H

    Keeps track of depth with each recursion and returns the sub-list in each stage. if the desired depth is passed, the node is discarded and its sublist is passed which effectively removes the desired node.

    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        static int depth = 0, levels = 0;
        
        if (!head) {levels = depth++; return NULL;}
        depth++;
        head->next = removeNthFromEnd (head->next, n);
        depth--;
        if (levels - depth + 1 == n) return head->next;
        return head;
    }

Log in to reply
 

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