Stack ADT and array implementation
A last-in, first-out list where every insertion and deletion happens at one end, the top.
Syllabus says: “Stacks and Queues - Stacks”
On this page · 19 sections
LIFO — Last In, First Out. Empty: top = −1. Full: top = MAX − 1. PUSH = ++top, POP = top−−.
A stack of steel plates at a sadya: the last plate washed goes on top and is the first one picked up.
A stack is an ordered list in which insertions (push) and deletions (pop) are made at one end called the top; it follows Last-In-First-Out order.
അവസാനം വന്നവൻ ആദ്യം പോകും!
Learning objectives
- Define the stack ADT and its LIFO behaviour.
- Write push, pop and peek for an array-based stack, with overflow and underflow checks (asked in KTU Nov 2025 Q2 and the model paper Q10a).
- Trace a sequence of stack operations and state the final top.
Prerequisites
One-dimensional arrays and indexing from 0; functions in C; global variables.
Introduction
Think of a pile of plates in a canteen: you put a clean plate on top, and the next person takes the top plate. The plate placed last is removed first. A stack organises data the same way, and that one restriction makes it the natural tool for undo, function calls and expression evaluation.
Definition
A stack is an ordered list in which insertions (push) and deletions (pop) are made at one end only, called the top. The element inserted last is the first one removed — Last In, First Out (LIFO).
| Operation | Meaning | Error condition |
|---|---|---|
| push(x) | insert x on top | overflow — stack is full |
| pop() | remove and return the top element | underflow — stack is empty |
| peek() / top() | return the top element without removing it | stack is empty |
| isEmpty(), isFull() | test the state | — |
Array implementation
Use an array stack[0 … MAX−1] and an integer top that holds the index of the top element. top = −1 means the stack is empty, and top = MAX−1 means it is full.
- Push(x): if top = MAX−1 report overflow; otherwise top ← top + 1 and stack[top] ← x.
- Pop(): if top = −1 report underflow; otherwise item ← stack[top], top ← top − 1, return item.
- Peek(): if top = −1 the stack is empty; otherwise return stack[top].
Order matters: push increments top before storing; pop reads before decrementing. In C these become stack[++top] = x and return stack[top--].
Popping does not erase anything from memory. The old value stays in the array, but it is no longer part of the stack because it lies above top. The next push simply overwrites it.
Where stacks are used
- Function calls: each call's local variables and return address live in a stack frame (the call stack).
- Undo/redo in editors and the browser Back button.
- Checking balanced brackets in source code.
- Converting and evaluating expressions (next lessons).
- Backtracking: maze solving, depth-first search.
Worked example
| Operation | Result | top | Array (index 0 … 3) | Bottom → top |
|---|---|---|---|---|
| push(10) | ok | 0 | [10 _ _ _] | 10 |
| push(20) | ok | 1 | [10 20 _ _] | 10 20 |
| push(30) | ok | 2 | [10 20 30 _] | 10 20 30 |
| pop | removed 30 | 1 | [10 20 _ _] | 10 20 |
| push(40) | ok | 2 | [10 20 40 _] | 10 20 40 |
| push(50) | ok | 3 | [10 20 40 50] | 10 20 40 50 |
| push(60) | OVERFLOW | 3 | [10 20 40 50] | 10 20 40 50 |
| pop | removed 50 | 2 | [10 20 40 _] | 10 20 40 |
| pop | removed 40 | 1 | [10 20 _ _] | 10 20 |
MAX = 4. “_” marks a slot that holds no live element.
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Algorithm / pseudocode
- 1top ← −1
- 2Push(x):
- 3if top = MAX − 1 then
- 4print "Stack overflow"; return
- 5top ← top + 1
- 6stack[top] ← x
- 7Pop():
- 8if top = −1 then
- 9print "Stack underflow"; return
- 10item ← stack[top]
- 11top ← top − 1; return item
- 12Peek():
- 13if top = −1 then
- 14print "Stack empty"; return
- 15return stack[top]
- 16end
C implementation
stack_array.ctested ✓ 200/200 cases/* Stack using an array — KTU PCCST303, Module 1
* top = -1 means empty. Overflow when top == MAX-1, underflow when top == -1.
* Input : MAX (1..100), then commands until EOF: PUSH x | POP | PEEK
* Output: one line per command, then the final state. */
#include <stdio.h>
#include <string.h>
#define CAP 100
int stack[CAP];
int top = -1;
int MAX;
void push(int x) {
if (top == MAX - 1) { printf("OVERFLOW\n"); return; }
top = top + 1;
stack[top] = x;
printf("PUSHED %d\n", x);
}
void pop(void) {
if (top == -1) { printf("UNDERFLOW\n"); return; }
int item = stack[top];
top = top - 1;
printf("POPPED %d\n", item);
}
void peek(void) {
if (top == -1) { printf("UNDERFLOW\n"); return; }
printf("PEEK %d\n", stack[top]);
}
int main(void) {
char cmd[16];
int x;
if (scanf("%d", &MAX) != 1 || MAX < 1 || MAX > CAP) return 1;
while (scanf("%15s", cmd) == 1) {
if (strcmp(cmd, "PUSH") == 0) { if (scanf("%d", &x) != 1) return 1; push(x); }
else if (strcmp(cmd, "POP") == 0) pop();
else if (strcmp(cmd, "PEEK") == 0) peek();
else return 1;
}
printf("STATE top=%d\nCONTENTS:", top); /* bottom -> top */
for (int i = 0; i <= top; i++) printf(" %d", stack[i]);
printf("\n");
return 0;
}
Sample run · MAX = 3 · real output from gcc
Input (stdin)
3 PUSH 10 PUSH 20 PUSH 30 PUSH 40 POP PEEK
Output (stdout)
PUSHED 10 PUSHED 20 PUSHED 30 OVERFLOW POPPED 30 PEEK 20 STATE top=1 CONTENTS: 10 20
Complexity
| Operation | Time | Reason |
|---|---|---|
| push | O(1) | one comparison, one increment, one store |
| pop | O(1) | one comparison, one read, one decrement |
| peek | O(1) | one read |
Array vs linked implementation
| Array stack | Linked stack (Module 2) |
|---|---|
| Fixed size — overflow possible | Grows until memory runs out |
| No pointer overhead; cache-friendly | Extra pointer per element |
| Very simple code | Needs malloc/free |
Edge cases
- Pop or peek on an empty stack → underflow; the state does not change.
- Push on a full stack → overflow; the state does not change.
- MAX = 1: a single push fills the stack.
Common mistakes
- Checking top = MAX instead of top = MAX − 1 for overflow (off by one).
- Storing first and then incrementing (stack[top++] = x) with top starting at −1 — this writes to stack[−1].
- Forgetting to return or print the popped value in the algorithm.
- Writing ‘delete the element’ — pop only moves top; nothing is erased.
Asked in KTU exams (2)
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- LIFO; one end (top). Empty: top = −1. Full: top = MAX − 1.
- Push: check full → top++ → stack[top] = x.
- Pop: check empty → item = stack[top] → top-- → return item.
- All operations O(1).
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 3 (Stacks and Queues) §3.1
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — §10.1 (Stacks and queues)
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)