List的Destructor不能删除最后一个节点 [英] 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:<数据< endl;
delete next;
}
}
Node()
{
next = NULL;
}
};
节点*头;
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 - >下一个;
}
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;
}
输出如下:
节点出口:1
节点出口:2
节点出口:3
节点出口:4
这是一个公共列表,你可以注意节点和列表的两个析构函数。我认为这个可以工作,但出来显示,最后一个节点不能删除。我也测试其他数量的节点。结果是一样的,最后一个节点不能被删除。感谢您的建议: - )。
更改您的析构函数打印
NULL
,因此 if
语句返回 / code>,并且cout行未被调用。 virtual〜Node()
{
cout<< Node is out:<数据< endl;
if(next!= NULL)
{
delete next;
}
}
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:-).
解决方案 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;
}
}
这篇关于List的Destructor不能删除最后一个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!