liveBook · Manning

Push

As explained in Fabulous Adventures in Data Structures and Algorithms

Push is a linked-list operation that adds a value to the front of a list and returns the resulting list.

Push adds a value to the front of a linked list and returns the resulting list. In an immutable structure, it leaves the original list unchanged. section 1.2 section 2.2

For an immutable list or stack, push has three useful consequences:

  • The new value becomes the first item, while the previous list becomes its tail. section 1.2
  • Each push returns a separate list value, so earlier versions remain available. section 2.2 section 1.2.2
  • Multiple lists can share the same tail, avoiding needless copying. section 2.2

Building and reversing a list

Starting with an empty list, repeated pushes such as Push(10), Push(20), and Push(30) produce 30, 20, 10. Reversing traverses that list and pushes each item onto a new empty list, yielding 10, 20, 30 while preserving the original. section 1.2.2 section 1.2

Listing 1.1 Example immutable linked list
sealed record LinkedList<T>(T? Value, LinkedList<T>? Tail)
{
    public static LinkedList<T> Empty = new (default, null);#1
    public LinkedList<T> Push(T value) => new (value, this);
    public bool IsEmpty => this == Empty; #2
 public override string ToString()
 {
     var s = "";
     for (var list = this; !list.IsEmpty; list = list.Tail!)
         s += list.Value + " "; #3
     return s;
    }
}

Inspect the compact C# implementation: Push constructs a new node whose tail is the current list, while Empty provides a valid starting object. section 1.2

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Defines the operation, implements it with a new head and shared tail, and connects it to reversal and covariance.
Examples
Uses chained integer pushes, stack versions, list reversal, and animal values pushed through a covariant stack.
What it assumes
Assumes C# generics and linked-list or stack terminology while introducing immutable empty objects and shared tails.
What you can do after
Build it from scratch in C# as a constant-time immutable prepend operation returning a new list or stack.
How it connects
Connects push to immutable linked lists, immutable stacks, extension methods, covariance, and structural sharing through shared tails.

Also explained in

Compare how 4 books explain push →

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.