Implement a fixed-capacity circular queue type with enqueue and dequeue that report "full" and "empty".
Solution
main.c
#include <stdbool.h>
#include <stdio.h>
#define CAP 3
typedef struct {
int items[CAP];
int head, count; /* head = index of the oldest item */
} Queue;
bool enqueue(Queue *q, int v) {
if (q->count == CAP)
return false;
q->items[(q->head + q->count) % CAP] = v; /* wrap around the end */
q->count++;
return true;
}
bool dequeue(Queue *q, int *v) {
if (q->count == 0)
return false;
*v = q->items[q->head];
q->head = (q->head + 1) % CAP;
q->count--;
return true;
}
int main(void) {
Queue q = {.head = 0, .count = 0};
for (int v = 1; v <= 4; v++)
if (!enqueue(&q, v))
printf("enqueue %d: queue full\n", v);
int v;
dequeue(&q, &v);
printf("dequeued %d\n", v);
enqueue(&q, 4);
printf("rest:");
while (dequeue(&q, &v))
printf(" %d", v);
printf("\n");
return 0;
}
Output Verified by compiling and running
enqueue 4: queue full
dequeued 1
rest: 2 3 4
The modulo makes indexes wrap around, so freed slots at the front are reused without moving any data. Keeping a count avoids the classic ambiguity of head == tail meaning both "full" and "empty".
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!