Question

I have to write a doubly linked list, I am trying to implement the erase(Type obj) method which takes an argument obj and traverses through the list and deletes every node which has the element obj.

The problem I am facing is, I am iterating through the linked list from front and when I find the node which has the obj element, I change the next/previous pointers of the the nodes before and after the node with obj element. However I am not DELETING the node with obj itself, as far as I know c++ has no garbage collection so the node which had obj is still somewhere hanging in the air. How do I delete that?

My erase()

template <typename Type>
int Double_list<Type>::erase( Type const &obj ) {
if (empty()){
    return 0;
}
if (size() == 1 && head()->retrieve() == obj){
    list_head = nullptr;
    list_tail = nullptr;
    list_size--;
    return 1;
}

//Counter to hold the number of items deleted
int count = 0;
    //Iterating through the linked list
for (Double_node<Type> *ptr = head(); ptr != nullptr; ptr = ptr->next()){
    if (ptr->retrieve() == obj){
        ptr->previous_node->next_node = ptr->next();
        ptr->next()->previous_node = ptr->previous();
        count++;
        // delete ptr; // This stops me from iterating through the for loop
        list_size--;
    }
}
return count;
}
Was it helpful?

Solution

While you traversing your list, you are doing it using pointer to nodes which is of type Double_node<Type> *, which means that it was allocated somewhere and could be deleted with simple delete ptr, but since you are using it also to get next element in list you have to be careful and remember it prematurely, so it should be something like:

Double_node<Type> *ptr_next = 0;
for (Double_node<Type> *ptr = head(); ptr != nullptr; ptr = ptr_next) {
     ptr_next = ptr->next ();
     if (ptr->retrieve() == obj){
     if (ptr->previous_node)
       ptr->previous_node->next_node = ptr->next();

     ptr->next()->previous_node = ptr->previous();
     count++;
     list_size--;
     delete ptr;
    }

I believe that should do the trick.

OTHER TIPS

There is a syntax when deleting pointers and objects called delete. example code:

obj *temp = getCurrentNode();
//set pointers in nodes to the correct places
delete temp; //This releases all of the memory used in the object back to the OS
temp = NULL;//good practice to set this to null, since it points to non-allocated memory
//but exiting the function will make the pointer 'temp' useless, anyway.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top