Exam-style question
Try this first
Explain why a program should test whether a stack is empty before using pop and test whether it is full before using push. Include the possible problem in each case and describe how peek differs from pop.
Model answer
What a good answer should say
- The program should test whether the stack is empty before pop so that it does not attempt to remove a value when no value is available.
- It should test whether the stack is full before push so that it does not attempt to add a value when the stack has reached its maximum capacity.
- Peek, or top, returns the value at the top of the stack without removing it, whereas pop returns the top value and removes it.
Explanation
Why this works
The tests prevent invalid operations at the boundaries of the stack. The distinction between peek and pop is whether the top element remains in the stack after its value is returned.
Common mistake
No common mistake is linked to this question yet.
