A stack is a list where you can only add or remove at one end, called the top. The last item pushed is the first one popped, a rule known as LIFO (last in, first out). Think of a pile of plates: you take the top plate, never one from the middle.
In this lesson you will learn
- The four stack operations: push, pop, peek and isEmpty
- How to build a stack on an array in C
- How to detect overflow and underflow
- A classic use: checking balanced brackets
- Where stacks appear in real programs
Stack Operations
| Operation | What it does | Time |
|---|---|---|
push(x) | Puts x on top | O(1) |
pop() | Removes and returns the top item | O(1) |
peek() | Looks at the top item without removing it | O(1) |
isEmpty() | Tells whether the stack has no items | O(1) |
Every operation touches only the top, so all of them run in constant time.
An Array-Based Stack in C
An array plus one integer, top, is enough. top holds the index of the top item and starts at -1 for an empty stack.
#include <stdio.h>
#include <stdbool.h>
#define CAP 5
typedef struct { int items[CAP]; int top; } Stack; /* top = index of top item, -1 if empty */
static bool push(Stack *s, int v) {
if (s->top == CAP - 1) return false; /* overflow */
s->items[++s->top] = v;
return true;
}
static bool pop(Stack *s, int *out) {
if (s->top == -1) return false; /* underflow */
*out = s->items[s->top--];
return true;
}
int main(void) {
Stack s = { .top = -1 };
for (int v = 1; v <= 6; v++)
if (!push(&s, v * 10)) printf("push %d failed: stack full\n", v * 10);
printf("top item: %d\n", s.items[s.top]);
int x;
while (pop(&s, &x)) printf("popped %d\n", x);
if (!pop(&s, &x)) printf("pop failed: stack empty\n");
return 0;
}
Output
push 60 failed: stack full
top item: 50
popped 50
popped 40
popped 30
popped 20
popped 10
pop failed: stack empty
- Overflow: the stack holds 5 items, so pushing 60 fails. The function reports it instead of writing past the array.
- Underflow: popping an empty stack fails the same way.
- Items come out in reverse order: 50, 40, 30, 20, 10. That reversal is what makes stacks useful.
s->items[++s->top] = vmovestopup first, then stores.s->items[s->top--]reads first, then moves down.
For a stack with no fixed limit, push and pop at the head of a linked list instead. Both ends stay O(1).
Checking Balanced Brackets With a Stack
Compilers check that every (, [ and { is closed in the right order. A stack does this neatly: push each opening bracket, and on each closing bracket pop and check that it matches.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/* Check that every bracket is closed in the right order. */
static bool balanced(const char *s) {
char stack[100];
int top = -1;
for (; *s; s++) {
if (strchr("([{", *s)) {
if (top == 99) return false;
stack[++top] = *s;
} else if (strchr(")]}", *s)) {
if (top == -1) return false;
char open = stack[top--];
if ((*s == ')' && open != '(') || (*s == ']' && open != '[') || (*s == '}' && open != '{'))
return false;
}
}
return top == -1;
}
int main(void) {
const char *tests[] = {"a[i] = (b + c) * {d}", "f(x[0)]", "((x)", "{[()()]}"};
for (int i = 0; i < 4; i++)
printf("%-22s %s\n", tests[i], balanced(tests[i]) ? "balanced" : "NOT balanced");
return 0;
}
Output
a[i] = (b + c) * {d} balanced
f(x[0)] NOT balanced
((x) NOT balanced
{[()()]} balanced
f(x[0)] fails because ) arrives while [ is on top. ((x) fails because one ( is still on the stack at the end. The whole check takes one pass, O(n).
Where Stacks Are Used
- Function calls: every call pushes a frame onto the call stack; every return pops it.
- Undo and back buttons: the latest action or page is undone first.
- Expression evaluation: converting and evaluating expressions such as
3 + 4 * 2. - Depth-first search: exploring a maze or a graph one path at a time.
Stack Mistakes to Avoid
- No overflow check. Pushing past the array writes over other memory.
- Popping an empty stack. Always check
top == -1first. - Off-by-one on
top. Decide whethertopis the index of the top item or the next free slot, and stick to it. - Deep recursion. Each call uses stack memory; very deep recursion can overflow the real call stack.
Practice Exercises
Exercise 1. Push 1, 2, 3, pop once, push 4. What is on top?
Show answer
4. The stack holds 1, 2, 4 from bottom to top.
Exercise 2. Write peek for the array stack.
Show answer
bool peek(const Stack *s, int *out) {
if (s->top == -1) return false;
*out = s->items[s->top];
return true;
}
Exercise 3. How can a stack reverse the string “CODE”?
Show answer
Push C, O, D, E, then pop four times: E, D, O, C.
Frequently Asked Questions
What is the difference between a stack and a queue?
A stack removes the newest item first (LIFO). A queue removes the oldest item first (FIFO). See Queue Data Structure in C.
Should I use an array or a linked list for a stack?
An array is simpler and faster when you know the maximum size. A linked list grows without limit but needs a malloc for every push.
What is a stack overflow error?
It usually means the program’s call stack ran out of space, most often because a recursive function never reached its base case.
Summary
- A stack adds and removes only at the top: last in, first out.
- Push, pop, peek and isEmpty all run in O(1).
- An array plus a
topindex is the simplest implementation; check for overflow and underflow. - Stacks power function calls, undo, bracket checking and depth-first search.
