. Advertisement .
..3..
. Advertisement .
..4..
How to write destructor for linked list c++? Below is my code
LinkedList::~LinkedList()
{
ListNode *ptr;
for (ptr = head; head; ptr = head)
{
head = head->next
delete ptr;
}
}
Please give me a few practical suggestions.
Instead of attempting to carefully analyze whether that overcompilated
for
-loop is right, why not make it much simpler with an elegantwhile
-loop?It can be run through a debugger, or through the wetware in your skull. Both will confirm that it works. Let’s take, for example, the following list.
This list can be used to generate statements.
ptr = head
changesptr
to 47head
is non-zero so enter loop.head = head->next
setshead
NULL.delete ptr
will removesingle_node
.ptr = head
setsptr
NULLhead
is NULL(0), exit loop.You’ve now deleted the last entry from the list.
head
is now set as NULL. This is all there is to it.It’s possible to do the same thing with a longer or empty list. You’ll still be able to use it. There’s no difference between a one-element and fifty-element listing.
A side note: I don’t like pointers being treated as booleans. I would rather have it written as follows:
This makes code more readable and doesn’t sacrifice performance (unless you are a brain-dead programmer). It’s all a matter taste.
Comment:
It will work. It will work. A zero value will be considered false. You’ll see that head->next is never used when head is NULL. This is because you have already exited the loop body (or not entered the body, if it is empty).
Any other pointer value you provide will be considered true, and you will enter the loop body or continue it.