This is for my data structure class. The textbook creates a LinkedBag using a Node class.
In implementing the remove for the LinkedBag, near the end, they do nodeToDeletePtr->setNext(nullptr). But then right after, they delete the entire node. My question is why did they need to do nodeToDeletePtr->setNext(nullptr)? Doesn't the entire memory for the node get deallocated, so we shouldn't really have to care? We are not even going to have access to the node, so what's the point of setting the nullptr. Or is it just good practice?
Then they do it another nullptr at the very end with:
nodeToDeletePtr = nullptr;
From what I understand, we set a pointer to nullptr so that we do not accidently use the pointer, since we just deallocated the memory it previously pointed to.
Doesn't the nodeToDeletePtr get wiped when the function ends? I'm very confused because sometimes I see the textbook assign nullptr when they are finished with the pointer, and sometimes they don't. So I'm wondering if setting it to nullptr is doing something more.
If someone could clarify whether my though process is right or not, I would greatly appreciate it. Thanks a lot.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
template < class ItemType>
bool LinkedBag<ItemType>::remove( const ItemType& anEntry)
{
Node<ItemType>* entryNodePtr = getPointerTo(anEntry);
bool canRemoveItem = !isEmpty() && (entryNodePtr != nullptr );
if (canRemoveItem)
{
// Copy data from first node to located node
entryNodePtr->setItem(headPtr->getItem());
// Delete first node
Node<ItemType>* nodeToDeletePtr = headPtr;
headPtr = headPtr->getNext();
// Return node to the system
nodeToDeletePtr->setNext( nullptr );
delete nodeToDeletePtr;
nodeToDeletePtr = nullptr ;
itemCount--;
} // end if
return canRemoveItem;
} // end remove
template < class ItemType>
class Node
{
private :
ItemType item; // A data item
Node<ItemType>* next; // Pointer to next node
public :
Node();
Node( const ItemType& anItem);
Node( const ItemType& anItem, Node<ItemType>* nextNodePtr);
void setItem( const ItemType& anItem);
void setNext(Node<ItemType>* nextNodePtr);
ItemType getItem() const ;
Node<ItemType>* getNext() const ;
}; // end Node
|