Sunday, October 18, 2009

Stack Top

The third stack operation is stack top. Stack top copies the item at the top of the stack; that is, it returns the data in the top element to the user but does not delete it. You might think of this operation as reading the stack top. Stack top can also result in underflow if the stack is empty.

Figure 5 traces these three operations in an example. We start with an empty stack and push 5 and 10 into the stack. At this point, the stack contains two entries. We then pop 10 from the top of the stack, leaving 5 as the only entry. After pushing 15, the stack again contains two entries. At this point, we retrieve the top entry, 15, using stack top. Note that stack top does not remove 15 from the stack; it is still the top element. We then pop 15, leaving 5 as the only entry. When 5 is popped, the stack is again empty. Note also how this example demonstrates the last In-first out operation of a stack. Although 5 was pushed first, it is the last to be popped.

No comments:

Post a Comment