The Stack
Improve your mental model of the stack data structure
A typical analogy for the stack data structure
is a stack of plates - a collection of items placed on top of one another. The
stack has two methods to add and remove items from it’s collection - push
and
pop
.
It is a data structure that works on the principle of last in, first out - meaning that the last item added to the stack is the first
one to be removed. The last one in is also the only one that can be read, sometimes via a getter method named peek
.
Use cases
The stack data structure is a great use case for managing function call stacks, browser history stacks and requirements that involve undo functionality.
The stack visualised
An interactive example of the stack data structure.
- 0
- 1
- 2
- 3
Implementation
Here is an implementation of the stack data structure in TypeScript, using an array to store it’s collection of items. I have included some non-essential methods
such as peek
, which observes the last element in the stack.