queue.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* queue.c -- the Queue type implementation*/
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "queue.h"
  5. /* local functions */
  6. static void CopyToNode(Item item, Node * pn);
  7. static void CopyToItem(Node * pn, Item * pi);
  8. void InitializeQueue(Queue * pq)
  9. {
  10. pq->front = pq->rear = NULL;
  11. pq->items = 0;
  12. }
  13. bool QueueIsFull(const Queue * pq)
  14. {
  15. return pq->items == MAXQUEUE;
  16. }
  17. bool QueueIsEmpty(const Queue * pq)
  18. {
  19. return pq->items == 0;
  20. }
  21. int QueueItemCount(const Queue * pq)
  22. {
  23. return pq->items;
  24. }
  25. bool EnQueue(Item item, Queue * pq)
  26. {
  27. Node * pnew;
  28. if (QueueIsFull(pq))
  29. return false;
  30. pnew = (Node *) malloc( sizeof(Node));
  31. if (pnew == NULL)
  32. {
  33. fprintf(stderr,"Unable to allocate memory!\n");
  34. exit(1);
  35. }
  36. CopyToNode(item, pnew);
  37. pnew->next = NULL;
  38. if (QueueIsEmpty(pq))
  39. pq->front = pnew; /* item goes to front */
  40. else
  41. pq->rear->next = pnew; /* link at end of queue */
  42. pq->rear = pnew; /* record location of end */
  43. pq->items++; /* one more item in queue */
  44. return true;
  45. }
  46. bool DeQueue(Item * pitem, Queue * pq)
  47. {
  48. Node * pt;
  49. if (QueueIsEmpty(pq))
  50. return false;
  51. CopyToItem(pq->front, pitem);
  52. pt = pq->front;
  53. pq->front = pq->front->next;
  54. free(pt);
  55. pq->items--;
  56. if (pq->items == 0)
  57. pq->rear = NULL;
  58. return true;
  59. }
  60. /* empty the queue */
  61. void EmptyTheQueue(Queue * pq)
  62. {
  63. Item dummy;
  64. while (!QueueIsEmpty(pq))
  65. DeQueue(&dummy, pq);
  66. }
  67. /* Local functions */
  68. static void CopyToNode(Item item, Node * pn)
  69. {
  70. pn->item = item;
  71. }
  72. static void CopyToItem(Node * pn, Item * pi)
  73. {
  74. *pi = pn->item;
  75. }