Data Structures
Circular Queue
A fixed-size queue can wrap its head and tail indexes around the array.
Circular Queue
circular_queue.c
#include <stdio.h>
int main(void) {
int count = ;
int queue[4] = {0, 0, 0, 0};
int head = 0;
int tail = 0;
for (int i = 0; i < count; i++) {
queue[tail] = (i + 1) * 10;
tail = (tail + 1) % 4;
}
int first = queue[head];
head = (head + 1) % 4;
int second = queue[head];
printf("first=%d second=%d tail=%d\n", first, second, tail);
return 0;
}
#include <stdio.h>
int main(void) {
int count = ;
int queue[4] = {0, 0, 0, 0};
int head = 0;
int tail = 0;
for (int i = 0; i < count; i++) {
queue[tail] = (i + 1) * 10;
tail = (tail + 1) % 4;
}
int first = queue[head];
head = (head + 1) % 4;
int second = queue[head];
printf("first=%d second=%d tail=%d\n", first, second, tail);
return 0;
}
#include <stdio.h>
int main(void) {
int count = ;
int queue[4] = {0, 0, 0, 0};
int head = 0;
int tail = 0;
for (int i = 0; i < count; i++) {
queue[tail] = (i + 1) * 10;
tail = (tail + 1) % 4;
}
int first = queue[head];
head = (head + 1) % 4;
int second = queue[head];
printf("first=%d second=%d tail=%d\n", first, second, tail);
return 0;
}
tail wrap
Modulo arithmetic moves the tail back to zero after the final slot.
first out
Reading from the head removes the oldest queued value first.