A stack is a list where you can only add or remove items at one end, called the top. Think of a pile of plates: you put a new plate on top and take the top plate off first. This rule is called LIFO: last in, first out. Stacks are small and simple, but they power the undo button, the browser’s back button, bracket checking in code editors and the way C itself keeps track of function calls.
In this lesson you will learn
- The stack operations: push, pop, peek and isEmpty
- Building a stack with an array, and handling overflow and underflow
- Building a stack with a linked list that grows as needed
- Checking balanced brackets with a stack
- Evaluating postfix expressions
You should know arrays, linked lists and structures in C.
A Stack Built on an Array
#include <stdio.h>
#include <stdbool.h>
#define MAX 5
/* A stack stored in an array: top is the index of the last item */
typedef struct {
int items[MAX];
int top; /* -1 means empty */
} Stack;
void init(Stack *s) { s->top = -1; }
bool isEmpty(const Stack *s) { return s->top == -1; }
bool isFull(const Stack *s) { return s->top == MAX - 1; }
bool push(Stack *s, int x) {
if (isFull(s)) { printf("push %d: overflow!\n", x); return false; }
s->items[++s->top] = x; /* move top up, then store */
return true;
}
bool pop(Stack *s, int *out) {
if (isEmpty(s)) { printf("pop: underflow!\n"); return false; }
*out = s->items[s->top--]; /* read, then move top down */
return true;
}
bool peek(const Stack *s, int *out) {
if (isEmpty(s)) return false;
*out = s->items[s->top];
return true;
}
void show(const Stack *s) {
printf("stack (bottom -> top): ");
for (int i = 0; i <= s->top; i++) printf("%d ", s->items[i]);
printf("\n");
}
int main(void) {
Stack s;
init(&s);
for (int i = 1; i <= 6; i++) push(&s, i * 10); /* the 6th push overflows */
show(&s);
int x;
if (peek(&s, &x)) printf("peek: %d\n", x);
while (pop(&s, &x)) printf("popped %d\n", x); /* last in, first out */
return 0;
}
Output
push 60: overflow!
stack (bottom -> top): 10 20 30 40 50
peek: 50
popped 50
popped 40
popped 30
popped 20
popped 10
pop: underflow!
topholds the index of the last item. An empty stack hastop == -1.- push moves
topup by one and stores the item there. pop reads the item attopand movestopdown. - peek looks at the top item without removing it.
- The array has room for only 5 items, so the sixth push reports overflow. Popping from an empty stack reports underflow. Always check for both.
- Items come out in the reverse order they went in: 50, 40, 30, 20, 10.
- Every operation is O(1): it does the same small amount of work however many items there are.
A Linked-List Stack and Two Classic Uses
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
/* A stack of chars built from a linked list: it grows as needed */
typedef struct Node { char ch; struct Node *next; } Node;
void push(Node **top, char c) {
Node *n = malloc(sizeof *n);
if (!n) { perror("malloc"); exit(1); }
n->ch = c;
n->next = *top; /* new node points to the old top */
*top = n;
}
char pop(Node **top) {
Node *n = *top;
char c = n->ch;
*top = n->next;
free(n);
return c;
}
void clear(Node **top) { while (*top) pop(top); }
/* 1. Balanced brackets: every closer must match the latest opener */
bool balanced(const char *s) {
Node *st = NULL;
for (; *s; s++) {
if (strchr("([{", *s)) push(&st, *s);
else if (strchr(")]}", *s)) {
if (!st) return false;
char open = pop(&st);
if ((*s == ')' && open != '(') || (*s == ']' && open != '[') ||
(*s == '}' && open != '{')) { clear(&st); return false; }
}
}
bool ok = (st == NULL);
clear(&st);
return ok;
}
/* 2. Evaluate a postfix expression such as "5 3 + 2 *" with an int stack */
int evalPostfix(const char *expr) {
int st[64], top = -1;
for (const char *p = expr; *p; p++) {
if (isdigit((unsigned char)*p)) st[++top] = *p - '0';
else if (strchr("+-*/", *p)) {
int b = st[top--], a = st[top--]; /* order matters for - and / */
st[++top] = *p == '+' ? a + b : *p == '-' ? a - b : *p == '*' ? a * b : a / b;
}
}
return st[top];
}
int main(void) {
const char *tests[] = { "{[()()]}", "([)]", "((a+b)*c", "printf(\"%d\", a[i]);" };
for (int i = 0; i < 4; i++)
printf("%-22s %s\n", tests[i], balanced(tests[i]) ? "balanced" : "NOT balanced");
printf("5 3 + 2 * = %d\n", evalPostfix("5 3 + 2 *"));
printf("9 2 - 3 4 * + = %d\n", evalPostfix("9 2 - 3 4 * +"));
return 0;
}
Output
{[()()]} balanced
([)] NOT balanced
((a+b)*c NOT balanced
printf("%d", a[i]); balanced
5 3 + 2 * = 16
9 2 - 3 4 * + = 19
- The linked-list stack has no fixed size.
pushcreates a node that points to the old top, and the head pointer becomes the new top.popfrees the top node. - The functions take
Node **top, a pointer to the head pointer, so they can change which node is at the top. - Balanced brackets: push every opening bracket. For each closing bracket, the top of the stack must be its matching opener. At the end the stack must be empty.
([)]fails because)arrives while[is on top. - Postfix expressions put the operator after its numbers:
5 3 + 2 *means (5 + 3) × 2. Push numbers; on an operator, pop two numbers, apply it and push the result. No brackets or precedence rules are needed. - When popping for
-and/, the first value popped is the right operand, so the order matters.
| Array stack | Linked-list stack | |
|---|---|---|
| Size | Fixed (or resized by hand) | Grows until memory runs out |
| Memory per item | Just the item | Item plus a pointer |
| Speed | Very fast, cache friendly | Fast, but needs malloc and free |
| Typical use | Known maximum size | Unknown or very variable size |
Where Stacks Are Used
- Function calls: each call gets a stack frame for its local variables; returning pops it. This is the “call stack” behind recursion.
- Undo: each action is pushed; undo pops the latest one.
- Browser back button: visited pages are pushed; back pops.
- Depth-first search in graphs, and the monotonic stack pattern for “next greater element” problems.
Common Mistakes
- Not checking for underflow before popping, which reads garbage or crashes.
- Off-by-one with
top: mixing up “index of the top item” and “number of items”. - Forgetting to free nodes left in a linked-list stack, which leaks memory.
- Popping operands in the wrong order for subtraction and division.
Practice Exercises
Exercise 1. Use a stack to reverse the string “DHAKA”.
Show answer
char s[] = "DHAKA", st[16];
int top = -1;
for (int i = 0; s[i]; i++) st[++top] = s[i]; /* push every letter */
for (int i = 0; top >= 0; i++) s[i] = st[top--]; /* pop them back */
printf("%s\n", s); /* AKAHD */
Exercise 2. Work out 6 2 / 3 1 - * by hand using a stack.
Show answer
Push 6, push 2. “/” pops 2 and 6 and pushes 6/2 = 3. Push 3, push 1. “-” pops 1 and 3 and pushes 3 – 1 = 2. “*” pops 2 and 3 and pushes 6. The answer is 6.
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), like a line at a ticket counter.
What is a stack overflow error in a program?
It happens when the call stack runs out of space, usually because a recursive function never reaches its base case. Each call adds a frame until the memory set aside for the stack is used up.
Summary
- A stack adds and removes items only at the top: last in, first out.
- Push, pop and peek are all O(1).
- Array stacks are simple and fast but have a fixed size; linked-list stacks can grow.
- Stacks check brackets, evaluate postfix expressions and track function calls.
Next: Skip List in C.
