Stacks
A stack is a data structure that stores data, similar to a stack of plates in a kitchen. You can put a plate on the top of the stack, and when you need a plate, you take it from the top of the stack.
The last plate that was added to the stack will be the first to be picked up from the stack:
Figure 5.1: Example of a stack
The preceding diagram depicts a stack of plates. Adding a plate to the pile is only possible by leaving that plate on top of the pile. To remove a plate from the pile of plates means to remove the plate that is on top of the pile.
A stack is a data structure that stores the data in a specific order similar to arrays and linked lists, with several constraints:
- Data elements in a stack can only be inserted at the end (
push
operation) - Data elements in a stack can only be deleted from the end (
pop
operation) - Only the last data element can be read from the stack (
peek
operation)
A stack data structure allows...