Circular Queue
A circular buffer reuses freed array positions instead of shifting elements after every removal.
What is Circular Queue?
A circular buffer reuses freed array positions instead of shifting elements after every removal.
Implement first-in, first-out processing.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
C and C++ code examples
main.c
#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
C++
main.cpp
#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.
C
Structures and operations are usually separate and allocation is explicit.
C++
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.