Home > database >  Deleting nodes recursively
Deleting nodes recursively

Time:07-08

I have created this function to recursively delete nodes from a doubly linked list. The issue here is that based on the call stack, it starts from the second so it does not delete the entire list. I can delete the remaining node from the method where I'm calling this but there should be a way around that. Is there a way of resolving this issue?

    void RecursiveClear(const Node* _curr) {
    if(_curr != nullptr) {
        //_curr->prev = _curr;
        _curr = _curr->next;
        RecursiveClear(_curr);
    }
    if (_curr != nullptr) {
        delete _curr;
    }
}

CodePudding user response:

First: Don't use a leading _.

You modify _curr in the function so by the time you end up at the delete the original pointer is gone. So don't do that, just call the function wiht the next value without modifying the local vbariable:

RecursiveClear(_curr->next);

You also shouldn't do a recursion like that because lists can be long. Your code is not tail recursive. Every node in the list will use up a little bit of stack space. For long lists this will overflow the stack and crash.

Use a temporary so you can reorder the operations to be tail recursive:

void RecursiveClear(const Node* curr) {
   if (curr != nullptr) {
        const Node *next = curr->next;
        delete curr;
        RecursiveClear(next);
    }
}
  • Related