Lesson contents

Circular linked lists

The last node links back to the first. Keep a stopping rule, such as counting visits or returning to the starting node.

Simple example

Follow four turns starting at 2. After 6 the link leads back to 2 again.

Start2→4→6
Result2 4 6 2
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{2, 4, 6};
    const following = [_]i64{1, 2, 0};
    var node: i64 = 0;
    var turn: i64 = 0;
    while (turn < 4) {
        try show(values[@intCast(node)]);
        node = following[@intCast(node)];
        turn += 1;
    }
}
Output
2
4
6
2
Advertisements

Everyday examples

Rotate class helpers

Helpers A, B and C take turns. A starts. Who takes the fourth turn?

StartA B C
ResultA

Three turns complete one trip around the ring. The next link returns to A.

Ride a circular shuttle

The stops are 4, 9 and 12. You board at 12. Which stop is next?

Start4 9 12
Result4

The last stop is linked to the first. You reach stop 4 without reversing direction.

Repeat a slideshow once

Slides 7, 3 and 8 repeat. Which slides should a one-cycle preview show if it starts at 3?

Start7 3 8
Result3 8 7

Count three slides and stop. Continuing until there is no next slide would keep the preview running.

Cost and limits

A ring has no final empty link. Following next until it is empty would never finish in a nonempty ring.