A queue on an array in C
Two indices chase each other around a fixed buffer.
#define QUEUE_CAP 8
typedef struct {
int items[QUEUE_CAP];
size_t head;
size_t count;
} Queue;
int enqueue(Queue *q, int value) {
if (q->count == QUEUE_CAP) {
return 0;
}
size_t tail = (q->head + q->count) % QUEUE_CAP;
q->items[tail] = value;
q->count++;
return 1;
}
int dequeue(Queue *q, int *out) {
if (q->count == 0) {
return 0;
}
*out = q->items[q->head];
q->head = (q->head + 1) % QUEUE_CAP;
q->count--;
return 1;
}
How it works
headis where you take from,tailwhere you add.- The modulo makes the buffer circular.
- Keeping a count distinguishes empty from full.
Keywords and builtins used here
dequeueenqueueifintreturnsize_tstructtypedef
The run, in numbers
- Lines
- 27
- Characters to type
- 423
- Tokens
- 152
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 91 seconds.
Step 5 of 5 in Lists & stacks, step 10 of 20 in Data structures & algorithms.