stacks - Stacks A stack is a dynamic(the elements can...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Stacks 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 top . 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. push(x) Input: the element to be added to our stack, S. Postcondition: S now contains x, and top has been updated appropriately if top == capacity - 1 expandStack() 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: pop() Input: None 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 error: underflow top = top - 1 return S[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
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 5

stacks - Stacks A stack is a dynamic(the elements can...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online