C++ recursive using global variable


  • 0
    T
    /**
     * 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) return NULL;
            
            ListNode* result = NULL;
            doRemove(head, n, result);
            
            if (result == NULL) {
                head = head->next;
            }
            else{
            result->next = result->next->next;
            }
            
            return head;
        }
        
        void doRemove(ListNode* node, int& n, ListNode*& result) {
            if (!node) return;
            doRemove(node->next, n, result);
            n = n-1;
            if (n == -1) result = node;
        }
    };
    

Log in to reply
 

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