Stack / queue / deque · push/pop amortized O(1)
Stack
Push, pop and peek on the end of a dynamic array, including underflow.
The full explanation, derivation and practice are in the lesson Stacks: last in, first out on the end of an array.
Implementation
The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.
namespace Bekadan.Dsa.Examples.StacksQueues;
/// <summary>A LIFO stack on the end of a dynamic array: push and pop are amortized O(1).</summary>
public sealed class ArrayStack<T>
{
private readonly List<T> _items = [];
public int Count => _items.Count;
public IReadOnlyList<T> BottomToTop => _items;
public void Push(T item)
{
_items.Add(item); // the end of the array is the top
}
public T Pop()
{
if (_items.Count == 0)
throw new InvalidOperationException("The stack is empty.");
T top = _items[^1];
_items.RemoveAt(_items.Count - 1); // removing the last element shifts nothing
return top;
}
public T Peek()
{
if (_items.Count == 0)
throw new InvalidOperationException("The stack is empty.");
return _items[^1];
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/StacksQueues/ArrayStack.cs
"""An array-backed LIFO stack."""
from typing import Generic, TypeVar
T = TypeVar("T")
class ArrayStack(Generic[T]):
"""LIFO on the end of a list: push and pop are amortized O(1)."""
def __init__(self) -> None:
self._items: list[T] = []
def __len__(self) -> int:
return len(self._items)
def bottom_to_top(self) -> list[T]:
return list(self._items)
def push(self, item: T) -> None:
self._items.append(item) # the end of the list is the top
def pop(self) -> T:
if not self._items:
raise IndexError("pop from an empty stack")
return self._items.pop() # removing the last element shifts nothing
def peek(self) -> T:
if not self._items:
raise IndexError("peek at an empty stack")
return self._items[-1]
Tested on CPython 3.14.0 · examples/python/dsa_examples/array_stack.py
package dev.bekadan.dsa.stacks;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
/** A LIFO stack on the end of an ArrayList: push and pop are amortized O(1). */
public final class ArrayStack<T> {
private final List<T> items = new ArrayList<>();
public int size() {
return items.size();
}
public List<T> bottomToTop() {
return List.copyOf(items);
}
public void push(T item) {
items.add(item); // the end of the list is the top
}
public T pop() {
if (items.isEmpty()) {
throw new NoSuchElementException("The stack is empty.");
}
return items.remove(items.size() - 1); // removing the last element shifts nothing
}
public T peek() {
if (items.isEmpty()) {
throw new NoSuchElementException("The stack is empty.");
}
return items.get(items.size() - 1);
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/stacks/ArrayStack.java
#pragma once
#include <stdexcept>
#include <utility>
#include <vector>
namespace bekadan::dsa {
// A LIFO stack on the end of a std::vector: push and pop are amortized O(1).
// (std::stack is the standard adapter for this; this class shows the mechanism.)
template <typename T>
class ArrayStack {
public:
[[nodiscard]] std::size_t size() const noexcept { return items_.size(); }
[[nodiscard]] const std::vector<T>& bottom_to_top() const noexcept { return items_; }
void push(T item) {
items_.push_back(std::move(item)); // the end of the vector is the top
}
T pop() {
if (items_.empty())
throw std::underflow_error("pop from an empty stack");
T top = std::move(items_.back());
items_.pop_back(); // removing the last element shifts nothing
return top;
}
[[nodiscard]] const T& peek() const {
if (items_.empty())
throw std::underflow_error("peek at an empty stack");
return items_.back();
}
private:
std::vector<T> items_;
};
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/array_stack.hpp