template<typename T>
List<T>::~List()
{
while(head->next !=NULL){
delete head;
head = head->next;
}
head = NULL;
}
我想删除链表中的所有节点,但我不知道代码失败的原因。
答案 0 :(得分:1)
我会选择以下解决方案。没有无效的内存访问,没有内存泄漏,并且在离开循环之前它会自动为head
分配NULL:
template<typename T>
List<T>::~List()
{
while (head)
{
Node<T> *next = head->next;
delete head;
head = next;
}
}
请注意,我猜测了节点类型,你必须用代码中的任何内容替换它。
答案 1 :(得分:0)
这可以帮助您删除链接列表的每个节点。
List<T> *current = head;
while (current != NULL)
{
next = current->next;
delete current;
current = next;
}