Z

Data Structures

Stacks, queues, trees, heaps & hash tables — how they store and retrieve

Choosing the right data structure is often what separates a slow program from a fast one. Each structure trades off how quickly you can insert, remove, search or order data.

Linear structures

Stacks (last-in, first-out) and queues (first-in, first-out) impose an access order — stacks power undo and recursion, queues power scheduling and BFS. Linked lists chain nodes with pointers, giving cheap insertion and deletion anywhere without shifting elements, at the cost of no random access.

Hierarchical & keyed structures

Binary search trees keep keys ordered so lookups, insertions and range queries run in O(log n) on a balanced tree. Heaps are partially-ordered trees that surface the minimum or maximum in O(log n) — the engine behind priority queues and heap sort. Hash tables map keys to buckets through a hash function for average O(1) lookup, at the cost of unordered storage and occasional collisions.

The visualizers below let you push, pop, insert and delete to see exactly how each structure rearranges itself.

Try it interactively

Prefer a focused tool?

Frequently asked questions

When should I use a hash table versus a binary search tree?

Use a hash table when you need fast key lookups and do not care about order — average O(1) access. Use a binary search tree when you need keys kept in sorted order, range queries, or ordered traversal — O(log n) operations on a balanced tree.

What is the difference between a stack and a queue?

A stack is last-in, first-out (LIFO): the most recently added item is removed first, like a stack of plates. A queue is first-in, first-out (FIFO): items are removed in the order they were added, like a line at a checkout.