List的析构函数无法删除最后一个节点

Destructor of List cannot delete the last node

本文关键字:删除 最后一个 节点 析构函数 List      更新时间:2023-10-16

这是我的测试代码:

#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;   
}

输出如下:

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

这是一个常见的列表,您可以注意Node和list的两个析构函数。我以为这个可以工作,但结果显示最后一个节点不能删除。我还测试了其他数量的节点。结果是一样的,最后一个节点不能删除。感谢您的建议:-)。

将析构函数更改为打印在if语句的外部。

正在调用析构函数,但是,在最后一个节点上,nextNULL,因此if语句返回false,而cout行没有被调用。

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