当前位置:   article > 正文

C++实现循环队列_循环队列的c++程序

循环队列的c++程序

一、队列的定义

  1. class CirQueue
  2. {
  3. public:
  4. CirQueue(int len)
  5. {
  6. this->m_Array = new int[len] {};
  7. this->m_Front_idx = 0;
  8. this->m_Rear_idx = 0;
  9. this->m_Len = len;
  10. }
  11. void Push(int data);
  12. void Delete();
  13. void Print();
  14. ~CirQueue()
  15. {
  16. if (this->m_Array != nullptr)
  17. {
  18. delete[] this->m_Array;
  19. this->m_Array = nullptr;
  20. }
  21. }
  22. private:
  23. int* m_Array;
  24. int m_Front_idx;
  25. int m_Rear_idx;
  26. int m_Len;
  27. };

二、插入

  1. void CirQueue::Push(int data)
  2. {
  3. if ((this->m_Rear_idx + 1) % this->m_Len == this->m_Front_idx)
  4. {
  5. cout << "队列已满,插入失败" << endl;
  6. return;
  7. }
  8. this->m_Array[this->m_Rear_idx] = data;
  9. this->m_Rear_idx = (this->m_Rear_idx + 1) % this->m_Len;
  10. }

三、删除

  1. void CirQueue::Delete()
  2. {
  3. if (this->m_Front_idx == this->m_Rear_idx)
  4. {
  5. cout << "队列为空,删除失败" << endl;
  6. return;
  7. }
  8. this->m_Array[this->m_Front_idx] = 0;
  9. this->m_Front_idx = (this->m_Front_idx + 1) % this->m_Len;
  10. }

四、整体展示

  1. #include <iostream>
  2. using namespace std;
  3. class CirQueue
  4. {
  5. public:
  6. CirQueue(int len)
  7. {
  8. this->m_Array = new int[len] {};
  9. this->m_Front_idx = 0;
  10. this->m_Rear_idx = 0;
  11. this->m_Len = len;
  12. }
  13. void Push(int data);
  14. void Delete();
  15. void Print();
  16. ~CirQueue()
  17. {
  18. if (this->m_Array != nullptr)
  19. {
  20. delete[] this->m_Array;
  21. this->m_Array = nullptr;
  22. }
  23. }
  24. private:
  25. int* m_Array;
  26. int m_Front_idx;
  27. int m_Rear_idx;
  28. int m_Len;
  29. };
  30. void CirQueue::Push(int data)
  31. {
  32. if ((this->m_Rear_idx + 1) % this->m_Len == this->m_Front_idx)
  33. {
  34. cout << "队列已满,插入失败" << endl;
  35. return;
  36. }
  37. this->m_Array[this->m_Rear_idx] = data;
  38. this->m_Rear_idx = (this->m_Rear_idx + 1) % this->m_Len;
  39. }
  40. void CirQueue::Delete()
  41. {
  42. if (this->m_Front_idx == this->m_Rear_idx)
  43. {
  44. cout << "队列为空,删除失败" << endl;
  45. return;
  46. }
  47. this->m_Array[this->m_Front_idx] = 0;
  48. this->m_Front_idx = (this->m_Front_idx + 1) % this->m_Len;
  49. }
  50. void CirQueue::Print()
  51. {
  52. for (int i = 0; i < this->m_Len - 1; ++i)
  53. {
  54. cout << this->m_Array[i] << " ";
  55. }
  56. cout << endl;
  57. }
  58. void Text()
  59. {
  60. CirQueue CQ(5);
  61. CQ.Push(5);
  62. CQ.Push(2);
  63. CQ.Push(3);
  64. CQ.Push(4);
  65. CQ.Print();
  66. CQ.Delete();
  67. CQ.Print();
  68. }
  69. int main()
  70. {
  71. Text();
  72. system("pause");
  73. return 0;
  74. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/707108
推荐阅读
相关标签
  

闽ICP备14008679号