Очередь Queue<T> (FIFO)

Массивы и коллекции

//C has no queue: a ring buffer, the indexes go round the array
constexpr int queueSize = 4;

typedef struct {
    int items[queueSize];
    int head;  //where the next item is taken from
    int count;
} Queue;

bool enqueue(Queue *queue, int value) {
    if (queue->count == queueSize) {
        return false; //the queue is full
    }
    queue->items[(queue->head + queue->count) % queueSize] = value;
    queue->count++;
    return true;
}

//the caller checks that the queue is not empty
int front(const Queue *queue) {
    return queue->items[queue->head];
}

int dequeue(Queue *queue) {
    int value = queue->items[queue->head];
    queue->head = (queue->head + 1) % queueSize;
    queue->count--;
    return value;
}

Queue intQueue = {};
enqueue(&intQueue, 1);
enqueue(&intQueue, 3);
enqueue(&intQueue, 5);

int top = front(&intQueue);
//top is 1
int first = dequeue(&intQueue);
//first is 1
int second = dequeue(&intQueue);
//second is 3

//the freed cells are used again: 9 goes to items[0]
enqueue(&intQueue, 7);
enqueue(&intQueue, 9);
int third = dequeue(&intQueue);
//third is 5
int count = intQueue.count;
//count is 2

printf("top is %d\n", top);
printf("first is %d\n", first);
printf("second is %d\n", second);
printf("third is %d\n", third);
printf("count is %d\n", count);