Double-ended queues
A deque lets you add or remove items at either end. Decide which end to use for each action.
Simple example
Start with 4 and 6 in order. Add 2 at the front and print the new order.
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 slots = [_]i64{0, 4, 6, 0};
var front: i64 = 1;
const back: i64 = 2;
front -= 1;
slots[@intCast(front)] = 2;
var i: i64 = front;
while (i <= back) {
try show(slots[@intCast(i)]);
i += 1;
}
}
2 4 6
Everyday examples
Add a replacement shuttle
Shuttles B and C are lined up. Shuttle A returns to cover the next trip. Place it first.
Insert at the front. The regular order of B and C stays the same.
Restock a two-sided display
Books 3 and 5 sit on a display open at both ends. Add book 7 on the right and take one from the left. Which books remain?
Append 7, then remove 3 from the other end.
Cancel the newest pickup
Pickups 6, 9 and 2 are queued. The newest customer cancels before service. What stays in line?
Remove 2 from the back. The front customer, 6, keeps their turn.
Cost and limits
A circular array or a doubly linked list can support both ends efficiently. Fast end operations do not automatically make middle insertion fast.