liveBook · Manning

Reversing

As explained in Fabulous Adventures in Data Structures and Algorithms

Reverse is a method that constructs a new immutable linked list containing the input list's items in reverse order.

Reversing an immutable linked list cannot rearrange its existing links: the original list must remain unchanged. Instead, walk the list and build a new one. Each item is pushed onto the front of the result, so the last item visited ends up first. section 1.2.2

public LinkedList<T> Reverse()
{
    var result = Empty;
    for (var list = this; !list.IsEmpty; list = list.Tail!)
        result = result.Push(list.Value!);
    return result;
}

The result starts empty. The loop visits each item once and uses Push to prepend it to a new list; it never changes the input. section 1.2.2

Order without mutation

Starting with 50 40 30 20 10, Reverse produces 10 20 30 40 50. Both lists can be printed afterward because the original is unchanged. Reversal takes O(n) time and O(n) extra memory. section 1.2.2

The same operation solves a less obvious problem in an immutable queue built from two stacks. Normally, Dequeue pops the dequeue stack. When that pop empties it but the enqueue stack still has items, reversing the enqueue stack makes it the new dequeue stack. That transfer restores the order needed for subsequent dequeues; the ordinary case remains an O(1) pop. section 2.4

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Works through an iterative C# implementation, unchanged-input behavior, and O(n) time and extra-memory costs.
Examples
Tests reversal of a five-item integer list and uses stack reversal in an enqueue-and-dequeue sequence.
What it assumes
Assumes familiarity with C# syntax; defines the linked-list shape and points readers unfamiliar with records or nullability marks to separate guidance.
What you can do after
Build it from scratch with an empty accumulator and repeated Push calls, then apply the same pattern to an immutable queue.
How it connects
Connects immutable linked lists and stack Push to two-stack immutable queues and Dequeue.

Also explained in

Compare how 3 books explain reversing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.