Destructor of List cannot delete the last node

久未见 提交于 2019-12-25 12:18:10

问题


Here is my test code:

#include <iostream>
#include <cstdlib>

using namespace std;

class List
{
    private:
        class Node{
            public:
                int data;
                Node* next;
            public:
                virtual ~Node()
                {
                    if (next != NULL)
                    {
                        cout << "Node is out: " << data << endl;
                        delete next;
                    }
                }
                Node()
                {
                    next = NULL;
                }
        };

        Node* head;
    public:
        virtual ~List()
        {
            if (head != NULL)
            {
                delete head;
            }
        }
        List()
        {
            head = NULL;
        }
    public:
        void AddNode(int data);
        void DeleteNode(int data);
        //....  
};

void List::AddNode(int data)
{
    Node* temp = new Node;
    temp -> data = data;

    if (head == NULL)
    {
        head = temp;
    }
    else
    {
        Node* ptr = head;
        while (ptr -> next != NULL)
        {
            ptr = ptr -> next;
        }
        ptr -> next = temp;
    }   

}

int main()
{
    List test_list;
    test_list.AddNode(1);
    test_list.AddNode(2);
    test_list.AddNode(3);
    test_list.AddNode(4);
    test_list.AddNode(5);

    return 0;   
}

The output is like this:

Node is out: 1
Node is out: 2
Node is out: 3
Node is out: 4

It a common list and you can pay attention to the two destructor function for Node and List. I thought this one can work but the out showed that the last node cannot be deleted. I also test for other number of nodes. The result is the same, last node cannot be deleted. Thanks ahead for your advices:-).


回答1:


Change your destructor to print on the outside of the if statement.

The destructor is being called, however, on your last node next is NULL, so the if statement returns false and the cout line is not being called.

virtual ~Node()
{
    cout << "Node is out: " << data << endl;                
    if (next != NULL)
    {        
        delete next;
    }
}


来源:https://stackoverflow.com/questions/22998753/destructor-of-list-cannot-delete-the-last-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!