Skip to content
StudyFame

Stack in C

A stack is like a pile of plates: you put a plate on the top and you take a plate from the top. The last plate you put is the first one you take. This rule is called LIFO (Last In, First Out), and it powers the undo button, the browser's back button and every function call your program makes.

In this lesson you will build a stack in two ways, with an array and with a linked list, write push, pop and peek, handle overflow and underflow, and use a stack to check balanced brackets.

What You Will Learn

  • The LIFO principle and stack terminology.
  • Stack operations: push, pop, peek, isEmpty, isFull.
  • How to implement a stack with an array.
  • How to implement a stack with a linked list.
  • Overflow and underflow conditions.
  • Applications: bracket matching, undo, recursion, expression evaluation.

Stack in C Explained

Exam definition: A stack is a linear data structure in which insertion and deletion take place at only one end, called the top. It follows the LIFO (Last In, First Out) principle. Insertion is called push and deletion is called pop. Pushing onto a full stack causes overflow; popping from an empty stack causes underflow.

Memory trick: A stack is a pile of plates in a wedding buffet. Waiters push clean plates on top, guests pop the top plate. peek = look at the top plate without taking it. Too many plates = the pile falls (overflow); no plates left = a guest waits empty-handed (underflow).

push 10, push 20, push 30          pop -> 30

   |    |       top -> | 30 |          |    |
   |    |              | 20 |   top -> | 20 |
   | 10 |              | 10 |          | 10 |
   +----+              +----+          +----+

Syntax: Stack Operations

OperationWhat it doesTime
push(x)Add x on topO(1)
pop()Remove and return the top elementO(1)
peek() / top()Return the top element without removing itO(1)
isEmpty()True if the stack has no elementsO(1)
isFull()True if the array stack has no room (array version only)O(1)
#define MAX 5
int stack[MAX];
int top = -1;                    /* -1 means empty */

/* push */  if (top == MAX - 1) overflow;  else stack[++top] = x;
/* pop  */  if (top == -1)      underflow; else x = stack[top--];
/* peek */  x = stack[top];

Example 1: Stack Using an Array

#include <stdio.h>

#define MAX 3

int stack[MAX];
int top = -1;

int is_empty(void) { return top == -1; }
int is_full(void)  { return top == MAX - 1; }

void push(int x)
{
    if (is_full())
    {
        printf("Overflow! cannot push %d\n", x);
        return;
    }
    stack[++top] = x;
    printf("Pushed %d\n", x);
}

int pop(void)
{
    if (is_empty())
    {
        printf("Underflow! stack is empty\n");
        return -1;
    }
    return stack[top--];
}

int peek(void)
{
    return is_empty() ? -1 : stack[top];
}

void display(void)
{
    int i;
    printf("Stack (top to bottom): ");
    for (i = top; i >= 0; i--)
        printf("%d ", stack[i]);
    printf("\n");
}

int main(void)
{
    push(10);
    push(20);
    push(30);
    push(40);                    /* stack is full */
    display();
    printf("Peek: %d\n", peek());
    printf("Popped %d\n", pop());
    printf("Popped %d\n", pop());
    display();
    printf("Popped %d\n", pop());
    pop();                       /* stack is empty */
    return 0;
}

Output

Pushed 10
Pushed 20
Pushed 30
Overflow! cannot push 40
Stack (top to bottom): 30 20 10
Peek: 30
Popped 30
Popped 20
Stack (top to bottom): 10
Popped 10
Underflow! stack is empty

Code Explanation

  1. top holds the index of the top element; -1 means the stack is empty.
  2. push first checks top == MAX - 1 (full). Then stack[++top] = x increments top first and stores x there.
  3. pop checks for empty, then stack[top--] returns the top value and moves top down.
  4. peek reads the top value without changing top.
  5. Pushing 40 into a stack of size 3 gives overflow; popping a fourth time gives underflow.
  6. Notice the order: 30, 20, 10 come out in reverse of the push order. That's LIFO.

How a Linked-List Stack Works

An array stack has a fixed size. A linked-list stack grows as needed: the head of the list is the top of the stack, so push = insert at the beginning and pop = delete from the beginning, both O(1).

push 30:  top ──► [30] ──► [20] ──► [10] ──► NULL
pop    :  top ──► [20] ──► [10] ──► NULL     (30 returned and freed)
PointArray stackLinked-list stack
SizeFixed (MAX)Grows until memory runs out
OverflowWhen top == MAX − 1Only if malloc fails
MemoryNo pointer overheadOne pointer per element
SpeedVery fast, cache-friendlymalloc/free on each push/pop

Example 2: Linked-List Stack and Balanced Brackets

#include <stdio.h>
#include <stdlib.h>

struct node
{
    char data;
    struct node *next;
};

void push(struct node **top, char c)
{
    struct node *n = malloc(sizeof *n);
    if (n == NULL)
        exit(1);
    n->data = c;
    n->next = *top;
    *top = n;
}

char pop(struct node **top)
{
    struct node *t = *top;
    char c;
    if (t == NULL)
        return '\0';                /* underflow */
    c = t->data;
    *top = t->next;
    free(t);
    return c;
}

int is_balanced(const char *expr)
{
    struct node *top = NULL;
    int ok = 1;
    char open;

    for (; *expr != '\0' && ok; expr++)
    {
        if (*expr == '(' || *expr == '[' || *expr == '{')
            push(&top, *expr);
        else if (*expr == ')' || *expr == ']' || *expr == '}')
        {
            open = pop(&top);
            if ((*expr == ')' && open != '(') ||
                (*expr == ']' && open != '[') ||
                (*expr == '}' && open != '{'))
                ok = 0;
        }
    }
    if (top != NULL)                /* unclosed brackets left */
        ok = 0;
    while (top != NULL)
        pop(&top);
    return ok;
}

int main(void)
{
    const char *tests[] = {"{a[b(c)d]e}", "(x + y) * [z]", "(a + b]", "((a)", "a + b)"};
    int i;

    for (i = 0; i < 5; i++)
        printf("%-14s : %s\n", tests[i], is_balanced(tests[i]) ? "Balanced" : "Not balanced");
    return 0;
}

Output

{a[b(c)d]e}    : Balanced
(x + y) * [z]  : Balanced
(a + b]        : Not balanced
((a)           : Not balanced
a + b)         : Not balanced
  • Every opening bracket is pushed. Every closing bracket pops and must match the most recent unclosed opening bracket: exactly what LIFO gives.
  • (a + b]: ] pops (, a mismatch.
  • ((a): one ( is still on the stack at the end.
  • a + b): ) tries to pop from an empty stack (underflow), so it fails.
  • Compilers use this same check to report "expected ')'" errors.

Important Points to Remember

  • Stack = LIFO; insert and delete only at the top.
  • Operations: push, pop, peek, all O(1).
  • Array stack: top = -1 empty, top = MAX - 1 full.
  • Overflow = push on full; underflow = pop on empty.
  • Linked-list stack: head is the top; no fixed size.
  • Applications: function calls (call stack), undo/redo, back button, bracket matching, infix-to-postfix, recursion.

Common Mistakes Beginners Make

MistakeWhat happensFix
No overflow check before pushWrites past the array (undefined behavior)Check top == MAX - 1 first
No underflow check before popReads stack[-1]Check top == -1 first
stack[top++] = x with top starting at −1Writes to index −1Use stack[++top] = x
Calling a stack FIFOWrong answer in examsStack is LIFO; queue is FIFO
Not freeing nodes in a list stackMemory leakPop everything before exit

Stack Practice Questions

  1. What is a stack? Why is it called LIFO?
  2. Define overflow and underflow.
  3. What is the initial value of top in an array stack, and why?
  4. Compare array and linked-list implementations of a stack.
  5. List four applications of a stack.
Show answers
  1. A linear structure where insertion and deletion happen only at the top; the last element pushed is the first popped.
  2. Overflow: pushing onto a full stack. Underflow: popping from an empty stack.
  3. −1, because there is no element yet and the first push goes to index 0.
  4. Array: fixed size, fast, no pointer overhead. Linked list: dynamic size, extra pointer and malloc per element.
  5. Function call stack, undo/redo, balanced bracket checking, expression conversion/evaluation, browser back button.

Coding Exercise

Use an array stack to convert a decimal number to binary: push the remainders of division by 2, then pop them. Convert 13, 37 and 255.

Show solution
#include <stdio.h>

#define MAX 32

void to_binary(unsigned int n)
{
    int stack[MAX], top = -1;
    unsigned int original = n;

    if (n == 0)
        stack[++top] = 0;
    while (n > 0)
    {
        stack[++top] = n % 2;      /* push remainder */
        n /= 2;
    }
    printf("%3u = ", original);
    while (top >= 0)
        printf("%d", stack[top--]); /* pop gives the bits in the right order */
    printf("\n");
}

int main(void)
{
    to_binary(13);
    to_binary(37);
    to_binary(255);
    return 0;
}
 13 = 1101
 37 = 100101
255 = 11111111

Remainders come out from the lowest bit to the highest; the stack reverses them.

Quick Quiz: Stack in C (MCQ)

  1. A stack follows:

    A) FIFO   B) LIFO   C) Priority order   D) Random order

  2. Popping from an empty stack is called:

    A) Overflow   B) Underflow   C) Leak   D) Crash

  3. Push 1, 2, 3, then pop twice. What is on top?

    A) 1   B) 2   C) 3   D) Empty

  4. In a linked-list stack, the top is the:

    A) Last node   B) Head node   C) Middle node   D) NULL

  5. Which uses a stack internally?

    A) Function calls and recursion   B) Printer queue   C) Binary search   D) Hash table

Show answers
  1. B: LIFO.
  2. B: underflow.
  3. A: 1.
  4. B: the head node.
  5. A: function calls and recursion.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

StackLIFO, one end (top)
Operationspush, pop, peek: O(1)
Empty / full (array)top = −1 / top = MAX − 1
OverflowPush on a full stack
UnderflowPop on an empty stack
List stackHead = top, dynamic size
UsesCall stack, undo, brackets, postfix

Frequently asked questions

What is a stack in data structures?
A linear structure where elements are added and removed only at the top, following LIFO.
What is the difference between stack overflow and underflow?
Overflow: pushing when the stack is full. Underflow: popping when it is empty.
How is a stack used to check balanced parentheses?
Push each opening bracket; on a closing bracket pop and compare; the stack must be empty at the end.

Remember

  • Stack = pile of plates: last on, first off.
  • Check full before push, empty before pop.

Next Topic

Next lesson: Queue in C. You will build a queue (FIFO) with an array and a linked list.