Skip to content
Part IA Michaelmas Term

Stacks and Search Survey

Stacks

A stack is a sequence with Last-In-First-Out (LIFO) discipline. The item next to be removed is the one most recently added.

OperationDescription
emptyThe empty stack
null sTest whether s is empty
top sReturn the element at the top
pop sDiscard the top element
push s xAdd x to the top

Lists as stacks

OCaml lists naturally implement stacks:

Stack operationList equivalent
push s xx :: s
top sList.hd s
pop sList.tl s

Both :: and hd operate on the head in O(1) time.

Imperative stacks

In conventional languages, a stack is typically implemented with an array and a pointer (stack pointer). The pointer tracks how many elements are in use. Most language processors use an internal stack to manage recursive function calls.

Search strategy survey

The choice of data structure determines the search strategy:

Search strategyData structureDiscipline
Depth-firstStackLIFO
Breadth-firstQueueFIFO
Best-firstPriority queueOrdered by heuristic
Iterative deepeningStack (DFS repeated)LIFO with depth bound

Store pending nodes in a priority queue ordered by a heuristic ranking function. The function estimates the distance from each node to a solution. If the estimate is good, the solution is located swiftly.

Priority queues can be implemented with sorted lists (slow), binary search trees (O(log n) average), or more sophisticated structures like heaps.

Summary

  • DFS: stack-based, space-efficient, incomplete for infinite trees.
  • BFS: queue-based, finds shortest path, space-hungry.
  • Iterative deepening: DFS repeated with increasing bounds, combines space efficiency of DFS with completeness of BFS.
  • Best-first: priority queue, uses domain knowledge for efficiency.