Does anybody know why do we need to use temp in the below code? why can't we
just directly delete top and let top point to the next node?
num = top->value;
delete top;
top = top->next;
//****************************************************
// Member function pop pops the value at the top *
// of the stack off, and copies it into the variable *
// passed as an argument. *
//****************************************************
template < class T >
void DynStack<T>::pop( T &num )
{
StackNode *temp; // Temporary pointer
// First make sure the stack isn't empty.
if (isEmpty())
{
cout << "The stack is empty.\n";
}
else // pop value off top of stack
{
num = top->value;
temp = top->next;
delete top;
top = temp;
}
}
why can't we just directly delete top and let top point to the next node?
After you've deleted top (i.e. deleted the StackNode that the pointer top is pointing at), how would you know what the next node is? You would need to know what the next node is so you can make the pointer top point to it. How would you know what the next node is?
After you've deleted top, the memory top is pointing to is not owned by you, if you are fortunate, the content remains unchanged and you could get the next node, otherwise, this memory is reused by another thread, you could no longer get next node.