List的析构函数无法删除最后一个节点
Destructor of List cannot delete the last node
这是我的测试代码:
#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
语句的外部。
正在调用析构函数,但是,在最后一个节点上,next
是NULL
,因此if
语句返回false
,而cout行没有被调用。
virtual ~Node()
{
cout << "Node is out: " << data << endl;
if (next != NULL)
{
delete next;
}
}
相关文章:
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- std::字符串擦除以删除最后一个字母
- 在弦乐器中删除最后一个字符
- 如何删除最后一个逗号
- 删除最后一个节点,并将尾部更新到最后一个节点
- 试图删除最后一个std ::向量元素时,程序会崩溃
- 有效地从 std::list 中删除最后一个元素
- std::vector::erase删除最后一个元素而不是第一个元素
- 如何删除最后一个字符
- getAverage() 删除最后一个元素
- 单链表删除最后一个节点
- C++密码程序,字符串在后排时不会删除最后一个字符
- 从链表c++中删除最后一个节点
- c++ STL vector.erase()总是删除最后一个元素
- Multi_index_container删除最后一个元素
- V8 C++,从数组中删除最后一个元素
- List的析构函数无法删除最后一个节点
- 链表删除最后一个节点c++
- 从使用sstream读取的单词中删除最后一个空格的最佳方法
- Visual Studio c++从字符串中删除最后一个字符