A stack and a queue are two of the simplest and most useful data structures. A stack is last in, first out (LIFO), like a pile of plates: you add and remove at the top. A queue is first in, first out (FIFO), like a ticket line: people join at the back and leave from the front. C has no built-in versions, so this lesson builds both on top of plain arrays, including a circular queue that reuses its slots, and uses a stack to check balanced brackets.
In this lesson you will learn
- Implementing a stack with an array and a
topcounter - Handling overflow and underflow safely
- Checking balanced brackets with a stack
- Building a circular queue with the
%operator - When to use an array or a linked list underneath
You should know arrays, structures and passing pointers to functions.
A Stack in an Array
#include <stdio.h>
#include <stdbool.h>
#define CAPACITY 5
/* A stack stored in a fixed array: last in, first out */
struct stack {
int items[CAPACITY];
int top; /* number of items; next free slot */
};
static bool push(struct stack *s, int x) {
if (s->top == CAPACITY) return false; /* overflow */
s->items[s->top++] = x;
return true;
}
static bool pop(struct stack *s, int *out) {
if (s->top == 0) return false; /* underflow */
*out = s->items[--s->top];
return true;
}
/* Check whether brackets in an expression are balanced */
static bool balanced(const char *expr) {
char st[100];
int top = 0;
for (const char *p = expr; *p; p++) {
if (*p == '(' || *p == '[' || *p == '{') {
if (top == 100) return false;
st[top++] = *p;
} else if (*p == ')' || *p == ']' || *p == '}') {
if (top == 0) return false;
char open = st[--top];
if ((*p == ')' && open != '(') || (*p == ']' && open != '[') ||
(*p == '}' && open != '{'))
return false;
}
}
return top == 0;
}
int main(void) {
struct stack s = {.top = 0};
for (int i = 1; i <= 6; i++) {
if (!push(&s, i * 10))
printf("push %d failed: stack full\n", i * 10);
}
int x;
while (pop(&s, &x))
printf("popped %d\n", x);
printf("pop on empty: %s\n", pop(&s, &x) ? "ok" : "failed");
const char *tests[] = {"a[i] = (b + c) * {d}", "(]", "((x)"};
for (int i = 0; i < 3; i++)
printf("%-22s %s\n", tests[i], balanced(tests[i]) ? "balanced" : "not balanced");
return 0;
}
Output
push 60 failed: stack full
popped 50
popped 40
popped 30
popped 20
popped 10
pop on empty: failed
a[i] = (b + c) * {d} balanced
(] not balanced
((x) not balanced
topcounts the items and is also the index of the next free slot.pushstores atitems[top]then increasestop;popdecreasestopthen reads. Both are O(1).- The array has a fixed capacity of 5, so the sixth push reports overflow instead of writing past the end of the array. Popping from an empty stack reports underflow.
- The functions return
booland pass the popped value through a pointer, so the caller always knows whether the operation worked. - The items come out in reverse order (50 first), which is the defining property of a stack.
balancedpushes every opening bracket and pops when it meets a closing one; the popped bracket must be the matching kind. The expression is balanced only if every bracket matched and the stack ends empty. Compilers and editors use the same idea.
A Circular Queue
#include <stdio.h>
#include <stdbool.h>
#define CAPACITY 4
/* A circular queue: first in, first out, reusing freed slots */
struct queue {
int items[CAPACITY];
int front; /* index of the first item */
int count; /* how many items are stored */
};
static bool enqueue(struct queue *q, int x) {
if (q->count == CAPACITY) return false;
int rear = (q->front + q->count) % CAPACITY; /* wrap around */
q->items[rear] = x;
q->count++;
return true;
}
static bool dequeue(struct queue *q, int *out) {
if (q->count == 0) return false;
*out = q->items[q->front];
q->front = (q->front + 1) % CAPACITY;
q->count--;
return true;
}
static void show(const struct queue *q) {
printf("queue (front=%d, count=%d):", q->front, q->count);
for (int i = 0; i < q->count; i++)
printf(" %d", q->items[(q->front + i) % CAPACITY]);
printf("\n");
}
int main(void) {
struct queue q = {.front = 0, .count = 0};
for (int t = 101; t <= 105; t++) {
if (enqueue(&q, t)) printf("ticket %d joined\n", t);
else printf("ticket %d turned away: queue full\n", t);
}
show(&q);
int served;
for (int i = 0; i < 2; i++) {
if (dequeue(&q, &served)) /* always check: the queue may be empty */
printf("served %d\n", served);
}
enqueue(&q, 106);
enqueue(&q, 107); /* these reuse the slots freed at the start */
show(&q);
return 0;
}
Output
ticket 101 joined
ticket 102 joined
ticket 103 joined
ticket 104 joined
ticket 105 turned away: queue full
queue (front=0, count=4): 101 102 103 104
served 101
served 102
queue (front=2, count=4): 103 104 106 107
- A queue removes from the front and adds at the back. If the front simply moved forward through a normal array, the slots before it would be wasted.
- A circular queue wraps around: the position after the last slot is slot 0 again.
(front + count) % CAPACITYfinds the back, andfront = (front + 1) % CAPACITYmoves the front. - After serving tickets 101 and 102, the new tickets 106 and 107 reused their slots, and
frontis now 2. The queue still prints in arrival order. - Storing
countseparately makes “full” and “empty” easy to tell apart, which is a common difficulty when a circular queue keeps onlyfrontandrearindexes. - The compiler warned when the result of
dequeuewas used without checking it, so the loop checks the return value before printing.
Stack and Queue Operations
| Stack (LIFO) | Queue (FIFO) | |
|---|---|---|
| Add | push at the top | enqueue at the back |
| Remove | pop from the top | dequeue from the front |
| Look without removing | peek / top | front |
| Time per operation | O(1) | O(1) |
| Typical uses | Undo, function calls, bracket matching, depth-first search | Print jobs, task scheduling, breadth-first search |
Both structures can also be built on a linked list, which removes the fixed capacity at the cost of one malloc per item.
Common Mistakes
- Not checking for a full stack or queue, which writes past the end of the array.
- Popping from an empty stack and reading a meaningless value.
- Moving the queue’s front forward without wrapping, so the queue reports “full” while most slots are empty.
- Confusing
topas “index of last item” in one function and “next free slot” in another. Pick one meaning and use it everywhere.
Practice Exercises
Exercise 1. Add a peek function to the stack that returns the top item without removing it.
Show answer
static bool peek(const struct stack *s, int *out) {
if (s->top == 0) return false;
*out = s->items[s->top - 1];
return true;
}
Exercise 2. Use the stack to reverse the string “CODE”.
Show answer
const char *word = "CODE";
char st[16];
int top = 0;
for (const char *p = word; *p; p++) st[top++] = *p; /* push each letter */
while (top > 0) putchar(st[--top]); /* pop: EDOC */
putchar('\n');
Frequently Asked Questions
What is a stack overflow in a C program?
Besides a full data-structure stack, the term also means the program’s call stack running out of space, usually because of very deep or endless recursion. The program then crashes.
How do I make a stack that can grow?
Allocate the array with malloc, and when it is full, double its size with realloc. Each push is still O(1) on average.
Summary
- A stack is LIFO: push and pop at the top.
- A queue is FIFO: enqueue at the back, dequeue from the front.
- Check for overflow and underflow on every operation.
- A circular queue uses
%to reuse slots in a fixed array.
Next: Sorting Algorithms in C.
