liveBook · Manning

First-in-last-out structure

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

Last-in-first-out is an access-ordering rule in which the most recently inserted item is removed first.

A first-in-last-out structure follows the LIFO rule: the most recently inserted item is the first item removed. Its basic operations are push, which adds an item, and pop, which removes and returns the newest item. section 1.5 section 2.2

public class Stack<T>: CustomStringConvertible {
    private var container: [T] = [T]()
    public func push(_ thing: T) { container.append(thing) }
    public func pop() -> T { return container.removeLast() }
    public var description: String { return container.description }
}

Implements a generic stack with Swift’s Array as backing storage: append for push and removeLast for pop. section 1.5

With an Array backing store, push appends at the right end and pop removes from that same end. An empty pop fails because Array.removeLast() has no item to remove; an isEmpty property supports safe traversal logic. section 2.2

Towers of Hanoi

Model each tower as a stack: push a disc onto a tower, then pop its top disc and push it onto another tower. The top-only rule naturally enforces legal moves, while recursion coordinates the transfers. section 1.5

Depth-first search

A DFS stack stores unexplored states. Popping the newest state drives the search deeper; when a path reaches a barrier, the stack exposes the latest decision point for backtracking. section 2.2

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

How deep it goes
Explains the ordering rule, implements push, pop, and isEmpty in Swift, and demonstrates recursive and search-based uses.
Examples
Demonstrates disc towers, recursive Hanoi transfers, and maze exploration with a generic DFS frontier.
What you can do after
Apply it via Swift’s Array to implement stacks for recursive algorithms and depth-first searches.
How it connects
Connects stacks with arrays, recursion, Towers of Hanoi, depth-first search, and backtracking.

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.