Creating and Deleting a Stack : Stacks in C++ – 3

Question. Create a stack using the linked list implementation of a stack. Also, given a stack, delete it.

Solution.

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;

return true;

}

—-

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)

{

Node *curr;

while ( *stack )

{

curr = (*stack) -> next;

delete *stack;

*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.

——

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: