A stack is a fundamental data structure in computer science that follows the LIFO principle, which stands for Last In, First Out.
That means the last element you push onto the stack is always the first one to come out.
Loading simulation...
Even though stacks sound simple, they power some of the most critical parts of modern software systems like:
In this chapter, I'll break down:
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle: the last item added is the first one removed.
A stack of plates is the standard analogy. New plates go on top, and the plate you take off is always the one most recently added. Removing a plate from the middle is not allowed; everything above it has to come off first.
Whenever you need to access the most recently added item first, a stack is a natural fit.
A stack supports four standard operations:
All four operations run in O(1) time, which is what makes stacks efficient.
There are two common ways to implement a stack from scratch, each with its own trade-offs.
The most common approach is to use an array.
You maintain two things:
top to track the index of the last inserted element. It is initially set to -1 to represent an empty stack.With this setup, you perform all stack operations at the end of the array, which makes them run in O(1) time.
stack[top] and then decrement top.top.top is still at -1, which means no elements have been added yet.The main limitation of this approach is that the stack size is fixed.
Once the array is full, you can't push new elements unless you manually resize it.
This is why many modern languages provide dynamic arrays (like ArrayList in Java or list in Python) that resize automatically.
Another popular way to implement a stack is by using a linked list.
In this approach, the head of the linked list represents the top of the stack.
That means:
Since all operations are focused at the head, they run in O(1) time, just like the array implementation.
Since the size of linked list is dynamic, you don't need to worry about resizing like you would with a static array.
The trade-off is that each node stores an extra pointer (next), which means more memory is used compared to a plain array.
In most real-world applications and coding interviews, you rarely need to implement a stack from scratch. Most modern languages provide a tested stack implementation in their standard library.
Java provides two main ways to work with stacks: Legacy stack class and recommended Deque interface.
ArrayDeque is faster and more memory-efficient than Stack. It supports all standard stack operations and is the preferred choice for new code.
10 quizzes