What is a Stack?
Solution and explanation
What it is
A stack is a linear data structure that follows LIFO – Last In, First Out. The last element added is the first one removed, like a stack of plates: you put a plate on top and take the top plate first.
push(10), push(20), push(30)
top -> | 30 |
| 20 |
| 10 |
+----+
pop() returns 30, then 20, then 10
Core operations (all O(1))
- push(x): place x on top.
- pop(): remove and return the top element.
- peek() / top(): read the top element without removing it.
- isEmpty(): check whether the stack has elements.
- size(): number of elements.
Implementation 1: using an array
class ArrayStack {
private final int[] items;
private int top = -1; // index of the top element
ArrayStack(int capacity) { items = new int[capacity]; }
void push(int x) {
if (top == items.length - 1) throw new RuntimeException("Stack overflow");
items[++top] = x;
}
int pop() {
if (top == -1) throw new RuntimeException("Stack underflow");
return items[top--];
}
int peek() { if (top == -1) throw new RuntimeException("Empty"); return items[top]; }
boolean isEmpty() { return top == -1; }
}
Implementation 2: using a linked list (no fixed capacity)
Push and pop at the head, both O(1).
class LinkedStack {
private static class Node { int data; Node next; Node(int d, Node n) { data = d; next = n; } }
private Node head;
void push(int x) { head = new Node(x, head); }
int pop() {
if (head == null) throw new RuntimeException("Stack underflow");
int value = head.data; head = head.next; return value;
}
int peek() { return head.data; }
boolean isEmpty() { return head == null; }
}
Using Java's built-in stack
Deque<Integer> stack = new ArrayDeque<>(); // preferred over the old Stack class
stack.push(10); stack.push(20); stack.push(30);
System.out.println(stack.pop()); // 30
System.out.println(stack.peek()); // 20
Output
30
20
Complexity
- push, pop, peek, isEmpty: O(1) time.
- Space: O(n) for n elements.
Applications
- Function calls: the call stack stores return addresses and local variables (recursion uses it).
- Undo in editors, back button in browsers.
- Expression evaluation and conversion (infix to postfix), syntax checking of brackets.
- Depth-first search and backtracking (maze solving).
- "Next greater element" style problems using a monotonic stack.
Advantages and disadvantages
- Very simple and fast; all main operations are O(1).
- Natural for nested or reversible processes.
- Only the top element is accessible; searching is O(n).
- An array-based stack has a fixed capacity (overflow) unless it resizes.
Note: pop or peek on an empty stack is "underflow"; push on a full fixed-size stack is "overflow". Always check isEmpty first.
