data structure --Queue(基于数组的实现)

「爱情、让人受尽委屈。」 2022-09-20 05:55 276阅读 0赞
  1. #include<iostream>
  2. using namespace std;
  3. const int maxqueue=10;
  4. template <class T>
  5. class ArrayQueue
  6. {
  7. public:
  8. ArrayQueue();
  9. bool empty() const;
  10. bool full() const;
  11. int size() const;
  12. void append(T &item);
  13. void serve();
  14. T& retrieve();
  15. void clear();
  16. private:
  17. int count;
  18. int front,rear;
  19. T array[maxqueue];
  20. };
  21. template <class T>
  22. ArrayQueue<T>::ArrayQueue()
  23. /*Pre: None
  24. Post: The Queue is initialized to be empty.*/
  25. {
  26. count=0;
  27. front=0;
  28. rear=maxqueue-1;
  29. }
  30. template <class T>
  31. bool ArrayQueue<T>::empty() const
  32. /*Pre: None
  33. Post: Return true if the Queue is empty,otherwise return false.*/
  34. {
  35. return count==0;
  36. }
  37. template <class T>
  38. bool ArrayQueue<T>::full() const
  39. /*Pre:None
  40. Post:If the queue is full,true is returned.Otherwise,false is returned*/
  41. {
  42. return count==10;
  43. }
  44. template <class T>
  45. int ArrayQueue<T>::size() const
  46. /*Pre:None
  47. Post:Return the number of entries in the queue.*/
  48. {
  49. return count;
  50. }
  51. template <class T>
  52. void ArrayQueue<T>::append(T &item)
  53. /*Pre: None
  54. Post: Item is added to the rear of the Queue if it is not full,otherwise the queue is left unchanged.*/
  55. {
  56. if(count<maxqueue)
  57. {
  58. count++;
  59. rear=((rear+1)==maxqueue)?0:(rear+1);
  60. array[rear]=item;
  61. }
  62. }
  63. template <class T>
  64. void ArrayQueue<T>::serve()
  65. /*Pre: None
  66. Post: The front of the Queue is removed if the queue is not empty.*/
  67. {
  68. if(count>0)
  69. {
  70. count--;
  71. front=((front+1)==maxqueue)?0:(front+1);
  72. }
  73. }
  74. template <class T>
  75. T& ArrayQueue<T>::retrieve()
  76. /*Pre: None
  77. Post: The front of the Queue is returnd if the queue is not empty.*/
  78. {
  79. if(count>0)
  80. return array[front];
  81. }
  82. template <class T>
  83. void ArrayQueue<T>::clear()
  84. /*Pre: None
  85. Post: The Queue is reset to be empty.*/
  86. {
  87. count=0;
  88. front=0;
  89. rear=maxqueue-1;
  90. }

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读