Structs & Data Structures · intermediate · ~10 min
Implement a FIFO queue with a circular buffer.
A queue: first in, first out. Adding goes at the back (enqueue); removing comes from the front (dequeue).
The classic array implementation is a ring buffer: a fixed-capacity array with head and len indices, indexed modulo capacity. Reuses storage without shifting.
typedef struct {
int *buf; size_t cap, len, head;
} queue_t;
int q_enq(queue_t *q, int v) {
if (q->len == q->cap) return -1;
q->buf[(q->head + q->len) % q->cap] = v;
q->len++; return 0;
}
cap on insert/remove — overflows past the array.(head + len) % cap (tail) with just len.