Stacks: push, pop, peek; array and linked implementations
A stack adds and removes at the top only: last in, first out. Watch push, pop and peek on array and linked implementations.
The idea
You add a clean plate to the top of the pile. You also take plates from the top.
The plate you put down last is the first one you pick up. A stack is a container with exactly this rule.
Intuition
push adds a value on top. Here 3, 8 and 5 arrived in that order, so 5 is on top.
pop removes the top value, so 5 comes out first. This rule is called last in, first out (LIFO).
peek is the third operation: it reads the top value without removing it. A stack never lets you reach into the middle.
Complexity
push, pop and peek touch only the top, so each takes O(1) time. Finding a value deep inside takes O(n).
Both versions change one slot or one pointer per operation. The stack size never enters the cost.
Both versions use O(n) space. The array reserves its slots up front, and the list pays one pointer per node.
The array is compact and cache friendly but has a fixed capacity. The list grows one node at a time and never overflows until memory runs out.
Pitfalls
pop or peek on an empty stack is an underflow. Check that the stack is not empty before you call them.
In the array version an unchecked pop reads data[-1]. Python wraps that around to the last slot, and other languages crash.
Variations
A dynamic array never overflows: when data[] is full, it copies the values into an array twice as big. Then push 5 fits.
Undo, bracket matching and depth-first search all keep their pending work on a stack.
Code
Pseudocode
data ← array of capacity slots, top ← -1
push(x):
if top = capacity - 1: error "overflow"
top ← top + 1
data[top] ← x
pop():
if top = -1: error "underflow"
x ← data[top]
top ← top - 1
return x
peek():
if top = -1: error "underflow"
return data[top]
Python
class ArrayStack:
def __init__(self, capacity):
self.data = [None] * capacity
self.top = -1
def push(self, x):
if self.top == len(self.data) - 1:
raise OverflowError("stack overflow")
self.top += 1
self.data[self.top] = x
def pop(self):
if self.top == -1:
raise IndexError("stack underflow")
x = self.data[self.top]
self.top -= 1
return x
def peek(self):
if self.top == -1:
raise IndexError("stack underflow")
return self.data[self.top]
JavaScript
class ArrayStack {
constructor(capacity) {
this.data = new Array(capacity).fill(null);
this.top = -1;
}
push(x) {
if (this.top === this.data.length - 1) throw new Error("stack overflow");
this.top++;
this.data[this.top] = x;
}
pop() {
if (this.top === -1) throw new Error("stack underflow");
const x = this.data[this.top];
this.top--;
return x;
}
peek() {
if (this.top === -1) throw new Error("stack underflow");
return this.data[this.top];
}
}
Java
class ArrayStack {
private final int[] data;
private int top = -1;
ArrayStack(int capacity) { data = new int[capacity]; }
void push(int x) {
if (top == data.length - 1) throw new IllegalStateException("stack overflow");
data[++top] = x;
}
int pop() {
if (top == -1) throw new IllegalStateException("stack underflow");
return data[top--];
}
int peek() {
if (top == -1) throw new IllegalStateException("stack underflow");
return data[top];
}
}
Cost at a glance
| Access | O(1) top / O(n) |
|---|---|
| Search | O(n) |
| Insert | O(1) push |
| Delete | O(1) pop |
| Space | O(n) |
Practice problems (6)
Overflow handling Warm-up
An array stack has 3 slots and already holds 4, 7 and 2, so top = 2. A caller runs push(8). What should a well-written push do?
State after a sequence Warm-up
The stack holds 5, 2, 8 from bottom to top. Follow the operations pop, pop, push 8, push 2, push 6, peek, pop, and answer each question before the step plays.
Implement a stack on an array Standard
Complete the class ArrayStack so it stores values in a fixed array data of capacity slots and an index top. Do not use the language's built-in list push or pop.
push(x)stores x and returns true, or returns false when the stack is full (overflow).pop()removes and returns the top value, or returns -1 when the stack is empty.peek()returns the top value without removing it, or -1 when empty.
The given runStack(capacity, ops) runs the operations and collects one result per operation (push: 1 or 0).
Baseball game score Standard
You keep score for a game with odd rules. Each string in ops is one of:
- an integer: a new score;
"+": a new score equal to the sum of the previous two valid scores;"D": a new score equal to double the previous valid score;"C": the previous valid score is cancelled and removed.
Return the sum of all valid scores after the last operation.
Spot the bug: pop returns the wrong value Standard
This array stack passes its push and peek tests, but pop returns the wrong value. Click the line with the bug, then fix it. Results follow the same rules as "Implement a stack on an array".
Implement a stack with a linked list Challenge
Complete LinkedStack using Node objects (a value and a next pointer) and a top pointer. Do not use an array to hold the values, and keep every operation O(1).
push(x)adds x on top.pop()removes and returns the top value, or -1 when the stack is empty.peek()returns the top value, or -1 when empty.size()returns the number of values.
The given runLinkedStack(ops) collects the results of pop, peek and size.
Related topics
Next on the path: Queues: enqueue, dequeue; circular buffer