Reputation: 39
template<typename T>
List<T>::~List()
{
while(head->next !=NULL){
delete head;
head = head->next;
}
head = NULL;
}
I want to delete all the nodes in the linked list, but I don' t know why the code fail.
Upvotes: 1
Views: 109
Reputation: 862
I would go with the following solution. No invalid memory access, no memory leak, and it automatically assigns NULL to head
before leaving the loop:
template<typename T>
List<T>::~List()
{
while (head)
{
Node<T> *next = head->next;
delete head;
head = next;
}
}
Please note that I made a guess with the node type and you have to replace it by whatever is present in your code.
Upvotes: 1
Reputation: 653
It depends what type the head variable is. If it is the class, you can even use "recursive" deleting in "head" (I mean node) destructor. Something similar to:
Node::~Node(){
if(this->next != nullptr)
delete this->next;
delete this->content;
}
If the node is internal struct, you need temporary pointer to next node as mentioned above:
template<typename T>
List<T>::~List()
{
struct nodeType *temp;
while(head != nullptr){
temp = head->next;
delete head;
head = temp;
}
}
In this case, you don't need to explicitly set head to null, since it is done by the logic of while loop.
In your loop (in question) you don't remove *head node, I don't know if it is expected behavior.
Ad. comment above (I can't put it directly): while(head->next!=NULL){ Node*next = head->next; delete head; head = next; } head = NULL; is wrong. It doesn't delete last node on the list (especially if the list has only one object, it won't be deleted).
Upvotes: 0
Reputation: 2491
This can help you in deleting every node of linked list.
List<T> *current = head;
while (current != NULL)
{
next = current->next;
delete current;
current = next;
}
Upvotes: 0
Reputation: 40060
Your code fails probably because it invokes undefined behaviour.
delete head;
head = head->next;
You cannot read the memory located where head
points after having delete
d head
.
You should make a copy of head->next
to reuse it:
const auto next = head->next;
delete head;
head = next;
Upvotes: 2