Creating and Deleting a Stack : Stacks in C++ – 3
February 12, 2011 Leave a comment
Question. Create a stack using the linked list implementation of a stack. Also, given a stack, delete it.
To create a stack, we do not need to do anything special. We simply need to set the head pointer to NULL.
We can do this as follows:
bool createStack ( Node **stack)
*stack = 0;
Note that we declare the return type to be bool, and return a true value. When implementing a stack as a linked list, creating the stack is trivial and there is no possibility of failure. However that may not be the case in case we implement the stack via other means. Hence, it is a good idea to include a boolean return value so that if one day someone decides to change the linked list implementation in favor of some other implementation, he may know that there is the possibility of failure in the creation of a stack.
In order to delete a given stack, we could call pop successively until no more nodes are left, or we could simply “delete” each node as we encounter it.
We could do that as follows.
bool deleteStack ( Node **stack)
while ( *stack )
curr = (*stack) -> next;
*stack = curr;
Note that we use pointer to a pointer in order to pass the head of the stack. Note also that we always need to store a pointer to the node which immediately follows the node we are deleting before we actually delete the node. Hence the need to have a “curr” pointer.