Circular Queue
Implement first-in, first-out processing.
What is Circular Queue?
A circular buffer reuses freed array positions instead of shifting elements after every removal.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
See how it works
Enqueue and dequeue to see that items leave in the same order they arrived.
C and C++ code examples
#include <stdio.h>
typedef struct {
int data[4];
int head;
int size;
} Queue;
int push(Queue *queue, int value) {
if (queue->size == 4) return 0;
int tail = (queue->head + queue->size) % 4;
queue->data[tail] = value;
++queue->size;
return 1;
}
int pop(Queue *queue, int *value) {
if (queue->size == 0) return 0;
*value = queue->data[queue->head];
queue->head = (queue->head + 1) % 4;
--queue->size;
return 1;
}
int main(void) {
Queue queue = {{0}, 0, 0};
int value;
push(&queue, 7);
push(&queue, 9);
pop(&queue, &value);
printf("%d\n", value);
}
7
#include <iostream>
#include <queue>
int main() {
std::queue<int> values;
values.push(7);
values.push(9);
std::cout << values.front() << '\n';
values.pop();
}
7
C and C++ comparison
The C queue tracks head and size and wraps indices with modulo. std::queue provides a container adapter with front, push, and pop.
Structures and operations are usually separate and allocation is explicit.
Classes and containers can preserve invariants and manage resources automatically.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add empty and capacity-boundary tests.
- Implement cleanup and verify no leaks remain.
- Compare operation complexity with a standard container.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challenges