Stacks

Illustration of a stack: vertical boxes showing push adds to the top and pop removes from the top
Illustration: stacks follow Last In, First Out (LIFO); push and pop operate on the top.

Stacks follow Last In, First Out (LIFO). Push adds to the top, pop removes from the top, peek reads without removing.

Example: Stacks across languages

javascript
class Stack {
  constructor() { this.items = []; }
  push(x) { this.items.push(x); }
  pop() { return this.items.length ? this.items.pop() : null; }
  peek() { return this.items.length ? this.items[this.items.length - 1] : null; }
  isEmpty() { return this.items.length === 0; }
}

python
class Stack:
    def __init__(self):
        self.items = []

    def push(self, x):
        self.items.append(x)

    def pop(self):
        return self.items.pop() if self.items else None

    def peek(self):
        return self.items[-1] if self.items else None

    def is_empty(self):
        return len(self.items) == 0

java
import java.util.ArrayDeque;

public class StackDemo {
  private ArrayDeque items = new ArrayDeque<>();

  public void push(int x) { items.push(x); }
  public Integer pop() { return items.isEmpty() ? null : items.pop(); }
  public Integer peek() { return items.peek(); }
  public boolean isEmpty() { return items.isEmpty(); }
}

Quick quiz

A stack removes the most recently added item first. True (A) or False (B)?

Back to top