Sunday, 4 September 2016

c++ - Writing a LinkedList destructor?




Is this a valid LinkedList destructor? I'm still sort of confused by them.



I want to make sure I'm understanding this correctly.



 LinkedList::~LinkedList()
{
ListNode *ptr;

for (ptr = head; head; ptr = head)

{
head = head->next
delete ptr;
}
}


So at the beginning of the loop, pointer ptr is set to hold the address of head, the first node in the list. head is then set to the next item, which will become the beginning of the list once this first deletion takes place. ptr is deleted, and so is the first node. With the first iteration of the loop, pointer is set to head again.



The thing that concerns me is reaching the very last node. The condition "head;" should check that it is not null, but I'm not sure if it will work.




Any help appreciated.


Answer



Why not do it much much simpler - with an elegant while-loop instead of trying to carefully analyze whether that overcompilcated for-loop is correct?



ListNode* current = head;
while( current != 0 ) {
ListNode* next = current->next;
delete current;
current = next;

}
head = 0;

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...