9.1 The Stack ADTA stack is used to store data such that the last item inserted is the first item removed. It is used to implement a last-in first-out (LIFO) type protocol. The stack is a linear data structure in which new items are added, or existing items are removed from the same end, commonly referred to as the top of the stack. The opposite end is known as the base. Consider the example in Figure 9.1.1, which illustrates new values being added to the top of the stack and one value being removed from the top. ![]() Figure 9.1.1: Abstract view of a stack: (a) pushing value 19; (b) pushing value 5; (c) resulting stack after 19 and 5 are added; and (d) popping top value.
The Stack ADT
To illustrate a simple use of the Stack ADT, we apply it to the problem of reversing a list of integer values. The values will be extracted from the user until a negative value is entered, which flags the end of the collection. The values will then be printed in reverse order from how they were entered. We could use a simple list for this problem, but a stack is ideal since the values can be pushed onto the stack as they are entered and then popped one at a time to print them in reverse order. A solution for this problem follows. PROMPT = "Enter an int value (<0 to end):" myStack = Stack() value = int(input( PROMPT )) while value >= 0 : myStack.push( value ) value = int(input( PROMPT )) while not myStack.isEmpty() : value = myStack.pop() print( value ) Suppose the user enters the following values, one at a time: 7 13 45 19 28 -1 When the outer ![]() Figure 9.1.2: Resulting stack after executing the sample application.
|