Pop from a Stack: Stacks in C++ – 2
February 12, 2011 Leave a comment
Question. We wish to pop the top-most node from the stack.
We could code it as follows:
//*stack denotes a pointer to the top node of the Stack.
//the data which is being popped is stored in *data.
//function returns false if Stack is empty; else, returns true.
bool pop ( Node **stack, void **data)
if (! (*stack) )
Node *myNode = *stack;
*data = (*stack)->data;
*stack = (*stack)->next;
We need to pass data and stack in the form of pointer to a pointer since we are changing their contents (i.e. the location they point to) within the function.
Further, referencing the pointer *data is valid even after we explicitly “delete” myNode because *data points to some other location in the heap and not to the location which was deallocated by the “delete” statement.
A related task could be to return (without deleting) the top-most node of a stack.We can accomplish this in a manner similar to the pop function.
bool return_top ( Node *stack, void **data)
if (! stack)
*data = stack -> data;
Note that unlike the pop function, the return_top function takes a simple pointer (instead of a pointer to a pointer) as an argument. This is because it does not need to change the location to which the head of the stack points to. If we were implementing the return_top function within a Stack class, we would have designated it as a const function signaling that it does not modify any of the members of the Stack class.
Another possible way to return the top node of a stack could be to actually return the top node (i.e. as a return value of the function). In this case, we would need to pass only one argument to the function (a pointer to the head of the stack). The error-checking (i.e. the stack being empty) can be done in the environment of the caller.
We could write it thus:
void* return_top ( Node *stack)
assert ( stack != 0);
return stack -> data;