Build a stack yourself
28 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Building a stack from scratch reveals how memory management works. You can implement a stack with a dynamic array or with a linked list.
Array-based stack with dynamic resizing
An array stack keeps a top index that starts at -1 and doubles the array only when it is full. Doubling makes push amortized O(1).
Example 1 · Dynamic Array Stack with Resizing
public class DynamicArrayStackDemo { static class ArrayStack { private int[] data = new int[2]; private int top = 0;
public void push(int val) { if (top == data.length) resize(); data[top++] = val; }
public int pop() { if (isEmpty()) throw new IllegalStateException("Stack underflow"); return data[--top]; }
public int peek() { if (isEmpty()) throw new IllegalStateException("Stack underflow"); return data[top - 1]; }
public boolean isEmpty() { return top == 0; } public int size() { return top; }
private void resize() { int[] bigger = new int[data.length * 2]; System.arraycopy(data, 0, bigger, 0, data.length); data = bigger; } }
public static void main(String[] args) { ArrayStack stack = new ArrayStack(); stack.push(10); stack.push(20); stack.push(30); System.out.println("Top: " + stack.peek()); System.out.println("Size: " + stack.size()); System.out.println("Popped: " + stack.pop()); }}Top: 30 Size: 3 Popped: 30
What this code does
- The initial capacity is 2 slots.
- Pushing 30 triggers
resize()which doubles capacity to 4 slots. pop()decrementstopand returns 30 in O(1) time.
Why not grow the array by one slot on every push? Allocating and copying on each push takes O(n), so n pushes cost O(n²) in total. Geometric growth spreads the copying cost over many pushes.
Trace with capacity 3: top starts at -1. push(5) makes top 0 and the array [5, _, _]. push(8) gives [5, 8, _]. push(12) gives [5, 8, 12] and the array is full, so a fixed-capacity stack would overflow on the next push. pop() reads array[2] = 12 and moves top back to 1.
In a generic Object stack, set a popped slot to null so the garbage collector can reclaim it.
topindex: points to the next available slot in the array.- Push operation: writes to
data[top++]in O(1) amortized time. - Pop operation: decrements
topand returns the item in O(1) time. - Resizing strategy: doubles array capacity to keep average cost low.
Linked-list stack implementation
A linked-list stack stores elements inside Node objects. A reference named head points to the top node.
push(x) creates a new node pointing to head and updates head. pop() reads head.val and advances head = head.next.
Example 2 · Linked List Stack Implementation
public class LinkedListStackDemo { static class LinkedStack { private static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
private Node head = null; private int size = 0;
public void push(int val) { head = new Node(val, head); size++; }
public int pop() { if (isEmpty()) throw new IllegalStateException("Stack underflow"); int val = head.val; head = head.next; size--; return val; }
public int peek() { if (isEmpty()) throw new IllegalStateException("Stack underflow"); return head.val; }
public boolean isEmpty() { return head == null; } public int size() { return size; } }
public static void main(String[] args) { LinkedStack stack = new LinkedStack(); stack.push(100); stack.push(200); System.out.println("Peek: " + stack.peek()); System.out.println("Popped: " + stack.pop()); System.out.println("Empty: " + stack.isEmpty()); }}Peek: 200 Popped: 200 Empty: false
What this code does
headpoints to the top node of the stack.- Pushing links a new node in front of the existing
head. - Popping advances
headtohead.nextin O(1) time.
Every push and pop runs in strict O(1) time without any resizing delays. However, each node requires extra memory for its pointer field.
Remember:
- Strict O(1) operations: no resizing spikes occur.
- Flexible capacity: the stack grows until heap memory is exhausted.
- Memory overhead: each node allocates an object header and next reference.
Handling underflow and overflow conditions
Underflow occurs when a program calls pop() or peek() on an empty stack. A robust stack throws an exception rather than returning invalid data.
Example 3 · Stack Underflow Guard Demo
public class StackUnderflowGuardDemo { static class SimpleStack { private int[] arr = new int[5]; private int count = 0;
public void push(int x) { arr[count++] = x; }
public int pop() { if (count == 0) { System.out.println("Guard triggered: stack is empty"); return -1; } return arr[--count]; } }
public static void main(String[] args) { SimpleStack stack = new SimpleStack(); stack.push(50); System.out.println("Pop: " + stack.pop()); System.out.println("Pop again: " + stack.pop()); }}Pop: 50 Guard triggered: stack is empty Pop again: -1
What this code does
- First pop removes 50, leaving the stack empty.
- Second pop checks
count == 0and safely avoids index bounds errors. - Defensive checks keep stack operations safe.
Overflow occurs when pushing to a fixed-size stack that has reached maximum capacity. Dynamic stacks prevent overflow by resizing the underlying array automatically. Checking boundary conditions early prevents corrupted stack states.
Remember:
- Stack underflow: attempting to read or remove from an empty stack.
- Stack overflow: attempting to push into a full fixed-capacity buffer.
- Defensive checks: throw
IllegalStateExceptionorNoSuchElementExceptionon illegal access.
Next step
Check your understanding
10 quick questions