Stacks
Last in, first out — and the call stack you already met.
Before you start
A **stack** is a data structure with only two operations: **push** (add to the top) and **pop** (remove from the top). Just those two. Not "remove from the middle" or "read the third one down" — just top-of-stack.
That restriction sounds limiting, but it maps naturally onto anything with nesting: function calls, brackets in an expression, browser history, undo. The last thing you pushed is the first thing you pop — LIFO, "last in, first out".
This lesson walks through push and pop on a simple array-backed stack, then shows the everyday application: matching brackets in ((a+b)*c).
Stack
last in, first outEmpty stack. top = 0. Push and pop always work at the top.
Step 1 of 6. An empty stack. A stack is an array with a `top` index. `top` points at the next free slot — when the stack is empty, it is 0. Only two operations matter: `push` adds to the top, `pop` removes from the top. Both are O(1) because they never move other elements.
Step 01 / 06
An empty stack
A stack is an array with a top index. top points at the next free slot — when the stack is empty, it is 0.
Only two operations matter: push adds to the top, pop removes from the top. Both are O(1) because they never move other elements.
// Array-backed stackstruct Stack { int data[100]; int top; // index of next free slot};void push(Stack *s, int val) { s->data[s->top++] = val; // O(1)}int pop(Stack *s) { return s->data[--s->top]; // O(1)}int peek(Stack *s) { return s->data[s->top - 1];}// Example: matching bracketsbool balanced(const char *str) { Stack s = { .top = 0 }; for (int i = 0; str[i]; i++) { if (str[i] == '(') push(&s, str[i]); else if (str[i] == ')') { if (s.top == 0) return false; pop(&s); } } return s.top == 0;}