Queue
A queue is a first-in, first-out collection. You enqueue at the back and dequeue at the front. The oldest item is the next one out.
Detailed Explanation
BFS, job workers, and any "fair" buffer of work are queues. In C the honest implementations are a circular buffer in an array, or a singly linked list that keeps both head and tail pointers.
The list version is easy to picture. Enqueue allocates a node and hangs it off tail->next, then moves tail. Dequeue takes head, advances head, and frees the node. Empty means head == NULL; remember to set tail = NULL in that case or the next enqueue writes through a freed tail.
The array version is faster. A naive "enqueue at data[len++], dequeue by memmoveing everything down" is O(n) per dequeue and will not survive a hot path. A circular buffer keeps head and len (or head and tail) and wraps indices with % cap, or with a power-of-two mask. Enqueue and dequeue stay O(1). Full and empty must be distinguishable: store a count, or waste one slot, or keep a flag.
A queue of work items often stores pointers. Ownership then needs a sentence: does dequeue transfer the pointer to the caller? If the producer malloc'd the job, the consumer frees it. If the queue is still holding jobs when you shut down, a drain loop has to free them.
Bounded queues are a concurrency tool as much as a data structure. A single-threaded queue does not need atomics. A queue shared by threads needs a mutex, or a purpose-built lock-free design that is easy to get wrong. Do not share a plain struct Queue across threads because it "only does pointer assigns."
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
struct Queue {
struct Node *head;
struct Node *tail;
};
static int enqueue(struct Queue *q, int value)
{
struct Node *n = malloc(sizeof *n);
if (n == NULL) {
return -1;
}
n->value = value;
n->next = NULL;
if (q->tail == NULL) {
q->head = q->tail = n;
} else {
q->tail->next = n;
q->tail = n;
}
return 0;
}
static int dequeue(struct Queue *q, int *out)
{
if (q->head == NULL) {
return -1;
}
struct Node *n = q->head;
*out = n->value;
q->head = n->next;
if (q->head == NULL) {
q->tail = NULL;
}
free(n);
return 0;
}
int main(void)
{
struct Queue q = { NULL, NULL };
enqueue(&q, 1);
enqueue(&q, 2);
int v;
dequeue(&q, &v);
printf("%d\n", v); /* prints: 1 */
dequeue(&q, &v);
printf("%d\n", v); /* prints: 2 */
return 0;
}Common Gotchas
After the last dequeue, `tail` still points at the freed node unless you clear it
the next enqueue writes `tail->next` into freed memory.
An array queue that `memmove`s on every dequeue is `O(n)`
use a circular buffer.
BFS is "a queue of nodes, plus a visited set"
the queue alone will revisit nodes in a graph and may never finish.
A queue of pointers is a lifetime API
document who frees, including the items left in the queue at shutdown.