Expert · Data structures in C · topic 47 of 60 · 25 min
Stacks
Explanation
The idea
Only the top of a stack is accessible: you push an item on top, and pop takes the most recently pushed item off. This order (LIFO) appears everywhere: the call stack of a program, the undo history in an editor, the back button in a browser, and parsers that match brackets.
An array-based stack
#define STACK_MAX 100
typedef struct {
int items[STACK_MAX];
int top; /* number of items; the next free slot */
} Stack;
void stack_init(Stack *s) { s->top = 0; }
int stack_empty(const Stack *s) { return s->top == 0; }
int push(Stack *s, int value) {
if (s->top == STACK_MAX) return -1; /* overflow: full */
s->items[s->top++] = value;
return 0;
}
int pop(Stack *s, int *out) {
if (s->top == 0) return -1; /* underflow: empty */
*out = s->items[--s->top];
return 0;
}
items: [ 7 | 3 | 9 | | | … ]
top = 3 → the next push goes to items[3]; pop returns items[2] (9)Array stacks are fast and need no malloc, but have a fixed maximum (or use a dynamic array from module 6 to grow). A linked-list stack (push_front and remove from the front) grows without limit but allocates per item.
Bracket matching
int balanced(const char *s) {
char st[256];
int top = 0;
for (; *s; s++) {
char c = *s;
if (c == '(' || c == '[' || c == '{') {
if (top == (int) sizeof st) return 0; /* too deep for this simple version */
st[top++] = c;
} else if (c == ')' || c == ']' || c == '}') {
char want = (c == ')') ? '(' : (c == ']') ? '[' : '{';
if (top == 0 || st[--top] != want) return 0;
}
}
return top == 0; /* nothing left open */
}
/* balanced("{[()]}") → 1, balanced("(]") → 0, balanced("((") → 0 */Other stack uses
- Evaluating postfix expressions (3 4 + 2 *): push numbers, pop two on an operator, push the result.
- Undo/redo: push each action; undo pops.
- Depth-first search and replacing recursion with an explicit stack (avoids stack overflow on deep inputs).
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Stacks · 1/6
In this lesson you will build a stack: last in, first out.
Prefer a video by a teacher? Find free videos on “stack data structure in c array linked list balanced parentheses” on YouTube ↗
In real life: Undo in a billing screen
A shop's billing terminal records each action (add item, change quantity, apply discount) on a stack. Pressing Undo pops the last action and reverses it, so the cashier can step back through mistakes in the correct order.
typedef struct { int kind; int item_id; int qty_before; } Action;
/* on each change: push(&undo_stack, action); on Undo: if (pop(&undo_stack, &a) == 0) revert(a); */Practice (0/3 done)
Push 1, push 2, push 3, pop, push 4, pop, pop. What was popped, in order?
The same stack algorithm in JavaScript, which runs here: write evalPostfix(expr) that evaluates a postfix expression with single-space-separated tokens, numbers and + - * /, using an array as a stack. "3 4 + 2 *" is 14. Return null if the expression is malformed (too few operands, or more than one value left).
Implement an int stack in C twice: once with a fixed array and overflow/underflow checks, once with a linked list. Write the same small test (push 1–5, pop 3 times, peek, pop until empty, pop once more) for both and confirm they behave identically, including the error on the last pop.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Queues and circular buffersData structures in C · same module
- Binary search treesData structures in C · same module
- StacksData Structures and Algorithms (DSA) for interviews · Stacks, queues and linked lists
- Stacks and queuesPython Programming · Algorithms, data structures and testing
- Queues, stacks and priority queuesJava Programming (Core to Spring Boot) · The collections framework
- Navigator basicsFlutter and Dart · Lists, navigation and forms
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which order does a stack follow?
Answer: LIFO
Last in, first out.
What is "stack underflow"?
Answer: Popping from an empty stack
Overflow is pushing onto a full one.
What is the time complexity of push and pop?
Answer: O(1)
Only the top is touched.
Which feature naturally uses a stack?
Answer: Undo in an editor
The last action is undone first.
Which Python list operations make a stack with O(1) push and pop?Related
Answer: append and pop()
Working at the end needs no shifting. Anything at index 0 shifts the whole list, O(n).
From Stacks
Which order does a stack follow?Related
Answer: Last In, First Out
A stack is LIFO: the most recently added item is removed first.
From Stacks and queues
Which order does a stack follow?Related
What does Navigator.pop(context) do?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “Data structures in C” before its exam: Queues and circular buffers, Binary search trees, Hash tables.
- Module 10 exam: Data structures in C · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Debugging and tools. 60 topics left in the course before the final exam.