Lesson contents

Doubly linked lists

Each node has a previous link and a next link. You can move in either direction from a node you already have.

Simple example

Start at the last node, which holds 7. Follow its previous link once and print 5.

Start3↔5↔7
Result5
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{3, 5, 7};
    const previous = [_]i64{-1, 0, 1};
    var tail: i64 = 2;
    tail = previous[@intCast(tail)];
    try show(values[@intCast(tail)]);
}
Output
5
Advertisements

Everyday examples

Go back one photo

Photos 20, 31 and 42 are neighbours. You are looking at 31. What does the Previous button show?

Start20↔31↔42
Result20

Follow the previous link of 31 to 20. Its next link still leads to 42.

Take a book out of a reading chain

Cards A, B and C are linked both ways. Remove B. Which two links need updating?

StartA↔B↔C
ResultA↔C

A must point forward to C and C must point back to A. Updating only one direction breaks the return trip.

Reverse a museum tour

Rooms 3, 8 and 5 form a two-way tour. From room 5, visit the previous room twice.

Start3↔8↔5
Result8 3

The previous link from 5 reaches 8. Following the previous link again reaches 3.

Cost and limits

A known node can be removed in constant time when you update both neighbours. Finding that node by value can still require a full walk.