Stacks, Queues, and Deques

All of the operations on stacks, queues, and deques are \(O(1)\).

Stack

Last-in-first-out.

Queue

First-in-first-out.

Abstraction

It’s easy to implement all of these in terms of a simpler existing, more general data structure, such as a doubly-linked list:

    node *firstNode()
    node *lastNode()
    void remove(node *n)
    void insertAfter(node *n, T e)
    void insertBefore(node *n, T e)

Deque

Traversal

Stacks and queues present fundamentally the same API.

Stack Queue Abstraction
push enqueue insert
pop dequeue remove
top front first
size size size
isEmpty isEmpty isEmpty

As such, they are drop-in replacements for one another. Looking forward to the next chapter, on trees, we can traverse a tree using either a stack or a queue. The resulting difference in behavior is one of the fundamental distinctions in all of Computer Science: depth versus breadth.

  traverse(\(v\))
   C.insert(\(v\))
   while not C.isEmpty()
    \(v\) = C.remove()
    visit(\(v\))
    if \(v\).left
     C.insert(\(v\).left)
    if \(v\).right
     C.insert(\(v\).right)