A stack is a data structure which contains an ordered set of data.
Stacks provide three methods for interaction:
- Push - adds data to the “top” of the stack
- Pop - returns and removes data from the “top” of the stack
- Peek - returns data from the “top” of the stack without removing it
Stacks mimic a physical “stack” of objects. Consider a set of gym weights.
Each plate has a weight (the data). The first plate you add, or push, onto the floor is both the bottom and top of the stack. Each weight added becomes the new top of the stack.
At any point, the only weight you can remove, or pop, from the stack is the top one. You can peek and read the top weight without removing it from the stack.
The last plate that you put down becomes the first, and only, one that you can access. This is a Last In, First Out or LIFO structure. A less frequently used term is First In, Last Out, or FILO.
What is another real-world example that follows the stack protocol of Last In, First Out?
Think about your web browser when you’re navigating between pages. Is there anything “stack-like” going on?