Stacks and Queues

Agenda

  1. Stacks
    • ... for delimiter pairing
    • ... for postfix expression evaluation
    • ... for tracking execution and backtracking
  2. Queues
    • ... for tracking execution and backtracking
    • ... for apportioning work
    • ... for fair scheduling (aka "round-robin" scheduling)
  3. Run-time analysis
  4. Closing remarks

Overview

While the list data structure is incredibly useful, both implementations we explored (array-backed and linked) have operations that run in $O(N)$ time, which make them non-ideal for use with large, growing collections of data.

By further restricting the list API, however — in particular, by isolating points of access to either the front or end of the data set — we can create data structures whose operations are all $O(1)$, and remain very useful in their own right.

1. Stacks

Stacks are linear data structures which only permit access to one "end" of the data collection. We can only append ("push") items onto the tail end (a.k.a. the "top") of a stack, and only the most recently added item can be removed ("popped"). The last item to be pushed onto a stack is therefore the first one to be popped off, which is why we refer to stacks as last-in, first out (LIFO) structures.

... for delimiter pairing

e.g., '(1 + 2 * (3 - (4 / 2) + 5) - (6 + 1))'

... for postfix expression (aka "reverse polish notation") evaluation

e.g., '(1 + 2) * 5' $\rightarrow$ '1 2 + 5 *'

... for tracking execution and backtracking

2. Queues

Queues are linear data structures wherein we are only permitted to append ("enqueue") items onto the rear, and remove ("dequeue") items from the front. The oldest item still in a queue is therefore the next one to be dequeued, which is why we refer to a queue as a first-in, first-out (FIFO) structure. It is helpful to think of a queue as being the model for a line at a typical supermarket checkout aisle (first customer in, first customer to be checked out).

... for tracking execution and backtracking

... for doling out work

... for fair scheduling (aka "round-robin" scheduling)

3. Run-time analysis

Stack & Queue implementations:

4. Closing remarks