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.
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;
}
}
2 4 6 2
Everyday examples
Rotate class helpers
Helpers A, B and C take turns. A starts. Who takes the fourth turn?
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?
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?
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.