Skip to content

Expert · Data structures in C · topic 47 of 60 · 25 min

Stacks

Explanation

A stack is last-in, first-out (LIFO): push adds on top, pop removes the top, peek looks at it. In C, a stack is easily built on an array with a top index (check for overflow and underflow) or on a linked list (push and pop at the head). Stacks power undo features, function calls, expression evaluation and bracket matching.

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

c
#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.

Careful: Popping an empty stack or pushing onto a full one must be detected. Without the checks, pop reads items[-1] and push writes past the array: both undefined behaviour. Every pop must check for empty, and callers must check pop's result.

Bracket matching

c
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).
Think of it like this: A stack is like a pile of plates in a hostel mess: you put clean plates on top and take from the top. The plate washed first is at the bottom and is used last.
Tip: For interviews, be able to write push, pop, peek and is_empty from memory for both the array and the linked-list versions, and explain the overflow and underflow checks.

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

Stacks

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.

c
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)

Task 1 · Question

Push 1, push 2, push 3, pop, push 4, pop, pop. What was popped, in order?

Task 2 · Code · Javascript

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).

Task 3 · Practice

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

Question 1

1.Which order does a stack follow?

Question 2

2.What is "stack underflow"?

Question 3

3.What is the time complexity of push and pop?

Question 4

4.Which feature naturally uses a stack?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

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

Answer: LIFO

Last in, first out.

From Queues, stacks and priority queues

What does Navigator.pop(context) do?Related

Answer: Removes the top screen from the stack

Back to the previous route.

From Navigator basics

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

  1. 3 more topics in “Data structures in C” before its exam: Queues and circular buffers, Binary search trees, Hash tables.
  2. Module 10 exam: Data structures in C · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Debugging and tools. 60 topics left in the course before the final exam.

← Previous: Singly linked lists