I like to handle this problem recursively:
void deleteNode(Node * head)
{
if(head->pNext != NULL)
{
deleteNode(head->pNext)
}
delete head;
}
If we have a list of 5 items:
head->pNext->pNext->pNext->pNext->NULL;
Then, the function will first get called for head, then for each pNext until the last one. When we reach the last one, it will skip deleting the next one (since it’s null) and just delete the last pNext. Then return and delete the list from back to front.
This is assuming that each node’s pNext is initialized to NULL. Otherwise, you’ll never know when you’ve reached the end of the linked list.
solved Is this a effective way to delete entire linked list?