0ms recursive solution

  • 0

    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;}
        head->next = removeNthFromEnd (head->next, n);
        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.