3.5. Using a Stack in C++
Now that we have clearly defined the stack as an abstract data type we
will turn our attention to using a stack with the help of the Standard Template Library (STL) in C++. Recall
that when we give an abstract data type a physical implementation we
refer to the implementation as a data structure.
As we described in Chapter 1, in C++, as in any object-oriented
programming language, the implementation of choice for an abstract data
type such as a stack is the creation of a new class. The stack
operations are implemented as methods. However, the STL already has a well
written implementation of the Stack class.
The following stack implementation (ActiveCode 1) assumes that
the end of the array will hold the top element of the stack. As the stack
push operations occur), new items will be added on the end
of the array.
pop operations will manipulate that same end.
Q-3: Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete?
cout << m.top();
- Remember that a stack is built from the bottom up.
- pay attention to the line that says m.pop();.
- Good job. This is correct because the 12 was poped of from the end and the 27 was pushed.
- The stack is empty
- This would mean everyting is removed from the stack, when does that happen?
Q-4: Given the following sequence of stack operations, what is the top item on the stack when the sequence is complete?
- You may want to check out the docs for
- the stack is empty
- There is an odd number of things on the stack but each time through the loop 2 things are popped.
- an error will occur
- Good Job, this is true because the stack can not evenly pop off every item within itself, because there is an odd number of items.
- You may want to check out the docs for isEmpty
You have attempted
activities on this page