A stack is the simplest useful data structure. It follows one rule: the last element added is always the first one removed. Think of a stack of plates — you always add to the top and always take from the top. You never reach into the middle. This single constraint — LIFO — makes the stack the backbone of function calls, expression evaluation, undo operations, and backtracking algorithms.
A stack is a collection of elements with a strict access rule: you can only interact with the top element. Adding an element places it on top. Removing an element takes it from the top. The element at the bottom is the oldest — and completely inaccessible until everything above it has been removed.
A stack has only four operations. All of them are O(1) — constant time regardless of how many elements the stack holds. This is what makes the stack both simple and powerful.
A stack is an abstract data type — the LIFO rule defines its behaviour, not its internal storage. It can be implemented using either an array or a linked list. Both give O(1) for all four operations, but they differ in memory behaviour.
top index pointer. Push increments top; pop decrements it.| Operation | Array Stack | Linked-List Stack | Notes |
|---|---|---|---|
| Push | O(1) | O(1) | Increment top / insert at head |
| Pop | O(1) | O(1) | Decrement top / remove head |
| Peek | O(1) | O(1) | Read arr[top] / read head.data |
| isEmpty | O(1) | O(1) | Check top == -1 / head == NULL |
| Search | O(n) | O(n) | Must pop until found — defeats the purpose |
| Space | O(n) | O(n) | Linked list uses extra n pointer words |
The Expression Evaluator demo shows the two-stack algorithm step by step — press Start on any preset expression then Step through it token by token, watching the Operand and Operator stacks change in real time. The Linear DS Quest lets you push and pop on a live stack.