Lesson contents

Queues

A queue takes new items at the back and serves waiting items from the front. Arrival order decides who goes next.

Simple example

Join the queue with 2, 5 and 8 in that order. Remove the front item and print 2.

Start2 5 8
Result2
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 {
    var queue = [_]i64{0, 0, 0};
    const arrivals = [_]i64{2, 5, 8};
    var front: i64 = 0;
    var back: i64 = 0;
    while (back < 3) {
        queue[@intCast(back)] = arrivals[@intCast(back)];
        back += 1;
    }
    const served: i64 = queue[@intCast(front)];
    front += 1;
    try show(served);
}
Output
2
Advertisements

Everyday examples

Call the next ticket

At a bakery, ticket 42 arrives before tickets 17 and 63. Which ticket should the counter call first?

Start42 17 63
Result42

Serve ticket 42. Sorting ticket numbers would put a later arrival first.

Send homework to a printer

Files A and B are waiting when file C arrives. Where does C go?

StartA B
ResultA B C

Add C at the back. The printer still takes A next.

Board the shuttle

Passengers 8, 5 and 7 are waiting. Two seats open. Who remains at the stop?

Start8 5 7
Result7

Remove the first two arrivals, 8 and 5. Passenger 7 becomes the front of the queue.

Cost and limits

Keeping a front and a back position avoids shifting every waiting item after a removal. An empty queue has no item to serve.