【发布时间】:2019-08-10 06:02:37
【问题描述】:
我无法通过析构函数删除我的列表。我有一个类 List(它充当列表的标题)和类 Element(它实际上是一个节点)。如何删除 List 析构函数中的 Element 链?
这是 C++ 中用于面试的自定义实现。我正在尝试使用 delete_list() 函数在列表生存期到期后删除整个列表。我不确定如何完全解决这个问题。我还有一个重载的运算符
/****************************************************************
* Template Element class, these make up the chain for the list
*****************************************************************/
template<class T>
class Element{
public:
T element;
Element* next;
Element() { element = 0; next = NULL; }
Element(const Element<T>& other): element(other.element), next(other.next) {};
~Element() { next = nullptr; }
};
/****************************************************************
* Template List class
*****************************************************************/
template<class N>
class List{
Element<N>* first;
unsigned size;
public:
/****************************************************************
* Constructors and Destructors
*****************************************************************/
List() { size = 0; first = nullptr; };
/* Constructor with input - for memory preallocation */
List(Element<N>* mem_destination){ size = 0; first = mem_destination; };
List(const List<N>& other): first(other.first), size(other.size) {};
~List(){ delete_list(); }
void delete_list()
{
Element<N>* iter;
size = 0;
while(first != nullptr)
{
iter = first->next;
delete first;
first = iter;
}
if(iter != nullptr)
{
delete iter;
iter = nullptr;
}
if(first != nullptr)
{
delete first;
first = nullptr;
}
}
friend std::ostream& operator<< (std::ostream& os, const List lista){
Element<N>* iter = lista.first;
os << "size: " << lista.size << std::endl;
while(iter != NULL){
os << iter->element << std::endl;
iter = iter->next;
}
if(iter != nullptr)
iter = nullptr;
return os;
}
...
【问题讨论】:
-
您的循环会删除所有节点。为什么你认为你需要删除更多? (查看您最喜欢的书中有关指针的部分。)
标签: c++ memory-management linked-list