Tail recursive 32 ms C++ function with helper


  • 0
    A
    ListNode* removeElements(ListNode* head, int val) {
            removeElementsHelper(head, val);
            return head;
        }
        void removeElementsHelper(ListNode* &head, int val){
            if (head == NULL)
                return;
            if (head->val == val){
                ListNode *tmp = head->next;
                if (tmp){
                    head->val = tmp->val;
                    head->next = tmp->next;
                    delete tmp;
                }
                else{
                    delete head;
                    head = NULL;
                }
                return removeElementsHelper(head, val);
            }
            return removeElementsHelper(head->next, val);
            
        }

Log in to reply
 

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