Pop from a Stack: Stacks in C++ – 2

Question. We wish to pop the top-most node from the stack.

Solution.

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) )

return false;

Node *myNode = *stack;

*data = (*stack)->data;

*stack = (*stack)->next;

delete myNode;

return true;

}

——

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)

return false;

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

}

—–

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: