There is something that I am not understanding about destructors of singly linked lists. When I have my destructor set as the code below, I have memory leaks.
LinkedList::~LinkedList()
{
Node *pDel = m_head;
/* Traverse the list and delete the node one by one from the head */
while (pDel != NULL) {
/* take out the head node */
m_head = m_head->m_next;
delete pDel;
/* update the head node */
pDel = m_head;
}
/* Reset the head and tail node */
m_tail = m_head = NULL;
}
In a single linked list when deleting a Node, you should make sure that the remaining Nodes remain connected to the head pointer, otherwise you might get objects that you can not delete anymore (memory leak).
If I understand your current code example correctly you want to delete the first Node of the list an repeat that until there are no more Nodes, while doing so you make sure that m_head points to the new head of the list before you delete the old head Node. I would think this is a valid way to do it.
Two other ways to do this that come to mind:
- The Node objects have their own destructor that deletes the next object before the Node is actually deleted. In this case, you could just give the command to delete the head of the list.
- You use recursion (or iterating) to find the last node, delete it, return to the new last node and so on until you delete the head of the list.