A stack is a dynamic (the elements can change) set for which the item to be removed is pre-
specified: we are only allowed to make deletions from a certain location. Similarly, we can only
access one element at a time. The delete operator of a stack removes the most recently added
item. For this reason, a stack is often referred to as a "Last in, First Out" structure, or LIFO for
short. Similarly, this is the only item we are allowed to look at in our stack. We come across
stack-like objects every day: a set of trays at Union South; the scoops on an ice cream cone; or a
Pez (tm) dispenser.
We can actually use an array to implement our stack. Let S be an array of capacity elements. That
is, the valid indices of S range from [0, 1, . . ., capacity-1]. We keep track of where we are going
to be inserting with a special index called
. That is, the top is the index of the most recently
added item. Thus, when the stack is empty, top == -1.
Let us write methods which insert, remove, and access our stack. We begin with insertion, which
is referred to as a "push" in stack-lingo.
Input: the element to be added to our stack, S.
Postcondition: S now contains x, and top has been updated
if top == capacity - 1
top = top + 1
S[top] = x
We define expandStack() in a manner similar to how we defined expandArray() in the previous
lecture: we double the capacity of the array, and copy all of the elements into the same indices.
To remove an item, we "pop" it off of the stack:
Returns: The item deleted from the stack
Postcondition: S no longer contains the popped item; top has been
updated to refer to the correct item
if top == -1
top = top - 1
As with previous structures, when we remove, we first make sure that there is an item to be
removed. That is, we avoid underflow.
Suppose we have a stack, initially empty, and have