当前位置:   article > 正文

用数组实现循环队列(c++)_数组实现环形队列c++

数组实现环形队列c++

一维数组在实现队列的时候会发生假溢出,此时我们需要用到循环队列。以下是一个粗略但是完整的代码。

  1. /* 数组实现循环队列 */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <iostream>
  5. using namespace std;
  6. #define MAX 6
  7. typedef struct{
  8. int* data;
  9. int front;
  10. int rear;
  11. }Queue;
  12. void init_queue(Queue &Q)//队列初始化
  13. {
  14. Q.data = (int*)malloc(sizeof(int)*MAX);
  15. Q.front = 0;
  16. Q.rear = 0;
  17. }
  18. bool empty_queue(Queue Q)//判空
  19. {
  20. return Q.front==Q.rear;
  21. }
  22. bool full_queue(Queue Q)///判队满
  23. {
  24. return (Q.rear+1)%MAX==Q.front;
  25. }
  26. bool push_queue(Queue &Q,int e)//入队
  27. {
  28. if(full_queue(Q)) return false;
  29. *(Q.data+Q.rear) = e;
  30. Q.rear = (Q.rear+1) % MAX;
  31. return true;
  32. }
  33. bool pop_queue(Queue &Q,int &e)//出队
  34. {
  35. if(empty_queue(Q)) return false;
  36. e = *(Q.data+Q.front);
  37. Q.front = (Q.front+1) % MAX;
  38. return true;
  39. }
  40. void print_queue(Queue Q)//打印队列
  41. {
  42. for (int i=Q.front;i!=Q.rear;i=(i+1)%MAX){
  43. cout << *(Q.data+i) << " ";
  44. }
  45. cout << endl;
  46. }
  47. int main()
  48. {
  49. Queue Q;
  50. char s;
  51. int e;
  52. init_queue(Q);
  53. while (1){
  54. cout << "i for insert and p for pop" << endl;
  55. cin >> s;
  56. if (s == 'i'){
  57. cout << "enter the element" << endl;
  58. cin >> e;
  59. if (push_queue(Q,e) == true) print_queue(Q);
  60. else{
  61. cout << "the queue is full" << endl;
  62. }
  63. }
  64. else if(s == 'p'){
  65. if (pop_queue(Q,e)==true) {
  66. cout << "the element poped is " << e << endl;
  67. print_queue(Q);
  68. }
  69. else {
  70. cout << "the queue is empty" << endl;
  71. }
  72. }
  73. }
  74. }

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

闽ICP备14008679号