Friday, April 16, 2010

In C++, how do you delete the last node from a dynamic linked list and set it to NULL?

If I call the destructor of a dynamic linked list of three or more nodes,





else if (head != NULL)


{


NodeType* currentPtr;





while (head-%26gt;link != NULL)


{


currentPtr = head;


while (currentPtr-%26gt;link != NULL)


{


currentPtr = currentPtr-%26gt;link;


}





delete currentPtr;


currentPtr = NULL;


}











delete head;


head = NULL;


}





What I observe is that currentPtr gets deleted as well as the last node, but while currentPtr gets set to NULL, the last node remains as garbage.





How can I also set the last node to null?

In C++, how do you delete the last node from a dynamic linked list and set it to NULL?
It looks like you are trying to delete the entire list. You have to save next before deleting current. You don't set the last node to NULL. You just delete it.


Try this





NodeType* currentPtr;


NodeType* nextPtr = head;


while (nextPtr != NULL)


{


currentPtr = next;


nextPtr = currentPtr-%26gt;link;


delete currentPtr;


}





If you want to delete a specific node, you have to know the one to delete and the one before it.





NodeType* currentPtr;


NodeType* prevPtr;


// find current and previous however it suits you


// such that prevPtr-%26gt;link points to current





// This steps takes the current node out of the list


prevPtr-%26gt;link = currentPtr-%26gt;link;


// then delete it


delete currentPtr;





// If current was the last node, current-%26gt;link would be null.


// The assignment prevPtr-%26gt;link = currentPtr-%26gt;link would make


// prevPtr-%26gt;link null automatically.


No comments:

Post a Comment