liveBook · Manning

Queue

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

A queue is a first-in-first-out data structure in which the earliest inserted item is removed first.

A queue removes items in the order they arrived: first in, first out (FIFO). Think of a line for a restroom—the first person to join is the first served. A stack does the opposite, removing the most recently added item first. section 2.2

In breadth-first search, a queue holds the frontier: states discovered but not yet checked. Adding successors at the back and taking the oldest state from the front checks nearby states before more distant ones. Replacing a depth-first search’s stack with a queue changes its search order without changing the basic search loop. section 2.2

public class Queue<T> {
    private var container: [T] = [T]()
    public var isEmpty: Bool { return container.isEmpty }
    public func push(thing: T) { container.append(thing) }
    public func pop() -> T { return container.removeFirst() }
}

The Swift implementation appends with push() and removes the first Array element with pop(); isEmpty lets the search loop check before popping. section 2.2

Finding a route

Starting in Boston, breadth-first search checks stations one stop away, then two stops away, and so on. When it reaches New York, it has already checked routes with fewer stops. The same queue-driven approach finds a shortest solution through the example maze. section 2.2

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines FIFO and implements a generic queue with Swift Array operations, without analyzing their performance.
Examples
Uses a restroom line, a train route, and a maze to illustrate arrival order and search order.
What it assumes
Assumes familiarity with Swift arrays and a stack-based depth-first search; defines FIFO through an everyday line.
What you can do after
Build it from scratch as a Swift Array-backed queue and use it as a breadth-first search frontier.
How it connects
Contrasts stacks and depth-first search with queues and breadth-first search.

Also explained in

Compare how 23 books explain queue →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.