← The C Language
Lesson 73 of 77 · 10 XP
The queue
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A queue is like a queue in a shop: we add to the end (enqueue) and take from the front (dequeue). First in, first out (FIFO).
On an array, a queue is made circular: the indices "wrap around" modulo the size, and the space freed at the start is used again.
#define CAP 8
int q[CAP];
int head = 0, count = 0;
int enqueue(int x)
{
if (count == CAP)
return 0; // full
q[(head + count) % CAP] = x;
count++;
return 1;
}
int dequeue(int *out)
{
if (count == 0)
return 0; // empty
*out = q[head];
head = (head + 1) % CAP;
count--;
return 1;
}
Queues are everywhere: print jobs, network packets, events in games, breadth-first graph traversal, the keyboard buffer in an OS.
Task. Implement a circular queue with a capacity of 3. The commands until the end of the input: push X (if the queue is full, print full) and pop (print the number or empty).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.