fork download
  1. #include <stdio.h>
  2. #include <stdlib.h> // For qsort
  3. #define QUEUESIZE 10 // Number of items the Queue can hold
  4. typedef enum { false, true } bool; // Use #include <stdbool.h> if available
  5.  
  6. typedef struct {
  7. char name[10];
  8. int priority;
  9. } Item;
  10.  
  11. Item *templist[QUEUESIZE]; // Used for sorting
  12.  
  13. typedef struct {
  14. Item *q[QUEUESIZE+1]; // queue container
  15. int first; // index of first element
  16. int last; // index of last element
  17. int count; // number of elements currently in queue
  18. } Queue;
  19.  
  20.  
  21. init_queue(Queue *q) {
  22. q->first = 0;
  23. q->last = QUEUESIZE-1;
  24. q->count = 0;
  25. }
  26.  
  27. int cmpfunc (const void * a, const void * b) {
  28. // Modify this function to do comparision on structure's other properties
  29. return ((*(Item**)a)->priority > (*(Item**)b)->priority);
  30. }
  31.  
  32. void enqueue(Queue *q, Item *x){
  33. if (q->count >= QUEUESIZE) {
  34. printf("Queue overflow\n");
  35. } else {
  36. q->last = (q->last+1) % QUEUESIZE;
  37. q->q[ q->last ] = x;
  38. q->count = q->count + 1;
  39. }
  40. }
  41.  
  42. Item *dequeue(Queue *q) {
  43. Item *x;
  44.  
  45. if (q->count <= 0) {
  46. printf("Queue empty\n");
  47. } else {
  48. x = q->q[ q->first ];
  49. q->first = (q->first+1) % QUEUESIZE;
  50. q->count = q->count - 1;
  51. }
  52.  
  53. return(x);
  54. }
  55.  
  56. void enqueue_with_priority(Queue *q, Item *x) {
  57. int i, count;
  58. enqueue(q, x);
  59. count = q->count;
  60. for(i=0; i < count; ++i) {
  61. templist[i] = dequeue(q);
  62. }
  63. qsort(templist, count, sizeof(Item *), cmpfunc);
  64. for(i=0; i < count; ++i ) {
  65. enqueue(q, templist[i]);
  66. }
  67.  
  68. }
  69.  
  70. int empty(Queue *q) {
  71. return q->count <= 0 ? true : false;
  72. }
  73.  
  74.  
  75. int main() {
  76. Queue item_queue;
  77. init_queue(&item_queue);
  78.  
  79. Item apple = {"apple", 10};
  80. Item ball = {"ball", 2};
  81. Item onion = {"onion", 8};
  82.  
  83. enqueue_with_priority(&item_queue, &apple);
  84. enqueue_with_priority(&item_queue, &ball);
  85. enqueue_with_priority(&item_queue, &onion);
  86.  
  87. dequeue(&item_queue);
  88. dequeue(&item_queue);
  89. dequeue(&item_queue);
  90.  
  91. return empty(&item_queue) ? 0 : -1;
  92. }
Success #stdin #stdout 0s 5500KB
stdin
Standard input is empty
stdout
Standard output is empty