Skip to content

Instantly share code, notes, and snippets.

@aatishnn
Created November 27, 2014 12:15
Show Gist options
  • Save aatishnn/21f16b8a3d178fa5417d to your computer and use it in GitHub Desktop.
Save aatishnn/21f16b8a3d178fa5417d to your computer and use it in GitHub Desktop.
Priority Circular Queue (Priority Queue inside Circular Queue) Implementation in C
#include <stdio.h>
#include <stdlib.h> // For qsort
#define QUEUESIZE 10 // Number of items the Queue can hold
typedef enum { false, true } bool; // Use #include <stdbool.h> if available
typedef struct {
char name[10];
int priority;
} Item;
Item *templist[QUEUESIZE]; // Used for sorting
typedef struct {
Item *q[QUEUESIZE+1]; // queue container
int first; // index of first element
int last; // index of last element
int count; // number of elements currently in queue
} Queue;
init_queue(Queue *q) {
q->first = 0;
q->last = QUEUESIZE-1;
q->count = 0;
}
int cmpfunc (const void * a, const void * b) {
// Modify this function to do comparision on structure's other properties
return ((*(Item**)a)->priority > (*(Item**)b)->priority);
}
void enqueue(Queue *q, Item *x){
if (q->count >= QUEUESIZE) {
printf("Queue overflow\n");
} else {
q->last = (q->last+1) % QUEUESIZE;
q->q[ q->last ] = x;
q->count = q->count + 1;
}
}
Item *dequeue(Queue *q) {
Item *x;
if (q->count <= 0) {
printf("Queue empty\n");
} else {
x = q->q[ q->first ];
q->first = (q->first+1) % QUEUESIZE;
q->count = q->count - 1;
}
return(x);
}
void enqueue_with_priority(Queue *q, Item *x) {
int i, count;
enqueue(q, x);
count = q->count;
for(i=0; i < count; ++i) {
templist[i] = dequeue(q);
}
qsort(templist, count, sizeof(Item *), cmpfunc);
for(i=0; i < count; ++i ) {
enqueue(q, templist[i]);
}
}
int empty(Queue *q) {
return q->count <= 0 ? true : false;
}
int main() {
Queue item_queue;
init_queue(&item_queue);
Item apple = {"apple", 10};
Item ball = {"ball", 2};
Item onion = {"onion", 8};
enqueue_with_priority(&item_queue, &apple);
enqueue_with_priority(&item_queue, &ball);
enqueue_with_priority(&item_queue, &onion);
dequeue(&item_queue);
dequeue(&item_queue);
dequeue(&item_queue);
return empty(&item_queue) ? 0 : -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment