Created
April 22, 2025 14:18
-
-
Save fabianbaechli/16cffabf5f1a99f668c6af1e6559625e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Queue { | |
int a[5]; // queue with 5 elements | |
int h; // head (first element of queue) | |
int t; // tail (right after last element) | |
}; | |
/* | |
This implementation can add infinite numbers of elements to the queue (even though it might be full) | |
because it is a circular queue implementation. If the array is full, elements are dropped. If this isn't reasonable | |
add a isFull check before adding | |
*/ | |
void enqueue(struct Queue* q, int val) { | |
q->a[q->t] = x; | |
q->t = (q->t + 1) % n; | |
} | |
int dequeue(struct Queue* q) { | |
int i = q->a[q->h]; | |
q->h = (q->h + 1) % n; | |
return i; | |
} | |
bool isFull(struct Queue* q) { | |
// q->t is guaranteed to be in bounds after last dequeue | |
// but q->t + 1 might be out of bounds, so we need to | |
// modulo again | |
return (q->t + 1) % n == q->h; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment