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.
using System;
int[] slots = new int[] { 0, 4, 6, 0 };
int front = 1;
int back = 2;
front -= 1;
slots[front] = 2;
int i = front;
while (i <= back) {
Console.WriteLine(slots[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.