Lesson contents

Singly linked lists

Each node stores a value and a link to the next node. Starting at the head, follow the links to read the list.

Simple example

Link the node holding 4 to 7, and 7 to 9. Print each value and stop when the last node has no next link.

Start4→7→9
Result4 7 9
lesson.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    const values = [_]i64{4, 7, 9};
    const following = [_]i64{1, 2, -1};
    var node: i64 = 0;
    while (node != -1) {
        try show(values[@intCast(node)]);
        node = following[@intCast(node)];
    }
}
Output
4
7
9
Advertisements

Everyday examples

Insert a stop on a bus route

The route goes from stop 4 straight to stop 9. Add stop 7 between them.

Start4→9
Result4→7→9

Point 7 at 9 first, then change the next stop after 4 to 7. The rest of the route stays reachable.

Follow a reading trail

Cards 11, 25 and 18 each name the next book to read. Which book comes after 25?

Start11→25→18
Result18

Follow the link on card 25. A larger or smaller book number tells you nothing about the order.

Remove a playlist entry

Tracks 2, 6 and 8 play in that order. Track 6 is unavailable. What should track 2 point to?

Start2→6→8
Result2→8

Copy track 6’s next link into track 2. Playing from 2 now skips straight to 8.

Cost and limits

Following a chain of n nodes takes linear time. Inserting directly after a known node takes constant time once the new node is available.