Stacks and queues are restricted linear collections that differ only in where elements are added and removed.

Stack (LIFO)

Last In, First Out: the most recently pushed element is popped first.

  • push(x): add to top, .
  • pop(): remove from top, .
  • peek(): inspect top without removing, .

Queue (FIFO)

First In, First Out: the oldest enqueued element is dequeued first.

  • enqueue(x): add to back, .
  • dequeue(): remove from front, .
  • front(): inspect front, .

Deques

A double-ended queue supports insertion and removal at both ends in .

  • Generalizes both stack and queue.
  • Usually backed by a doubly linked list or a circular dynamic array.

Array vs Linked Implementations

AspectArray-backedLinked-list-backed
Push/pop amortized worst case
Memorycontiguous, less overheadpointer per node
Resizingoccasional copynone needed

Queue via array

Use a circular buffer (wrap indices with modulo) so both ends operate in without shifting.

Applications

  • Call stack: function calls push frames, returns pop them; recursion depth bounded by stack size.
  • Expression evaluation and matching brackets use a stack.
  • Breadth-first search in Graphs uses a queue to visit nodes level by level.
  • Undo/redo and backtracking use stacks.