vendredi 29 janvier 2021

How do I use the destructor of an element of a doubly linked list? [closed]

My problem is the following, I have implemented a list in a class, which takes objects of type ListElement, where ListElements have a pointer to the next and previous list element. As in the example...

template <class value>
class ListElement
{

public:

    value content;
    ListElement* next;
    ListElement* previous;

    ListElement(value content, ListElement* next, ListElement* previous){
        this->content = content;
        this->next = next;
        this->previous = previous;
    };
    ~ListElement(){
        this->next = NULL;
        this->previous = NULL;
    };

};

template <class value>
class List : public Collection<value>
{

private:
    List<value>* first;
    Node<value>* last;


public:
    ListElement(){
        this->first = nullptr;
        this->last = nullptr;
    };
    ~ListElement(){
        if(!(this->isEmpty())){
             this->clear();
        }
        else{
            delete this->first;
            delete this->last;
        }
    };

    void clear(){
        Node<value>* currentNode = this->first, *nextNode = NULL;
    
        while (currentNode != NULL)
        {
            nextNode = currentNode->next;
            delete currentNode;
            currentNode = nextNode;
        }
    };
    

     void add(value t);
    
}

Now my question is how the destructor for a ListElement has to look like, with my solution so far it works, but i get an error when i check with valgrind for memory leaks.

The constructor of list element sets the next and the previous element, the destructor sets them to zero, the "content" can be ignored in this case, because I tried this only with int. When in destructor for ListElement delete this->next is executed I get a Segmentation Fault

Would be happy if someone could help me.

Aucun commentaire:

Enregistrer un commentaire