循环队列的C++实现

  1 #include <iostream>
  3 using namespace std;
  5 const int N=6;  //队列长度
  7 int a[N];      //队列数组
  9 int head;  //头指针的位置
 11 int tail;   //
 15 void init();   //初始
17 void add(int x); //队列入队 18 19 int out(); //队列出队 20 21 bool iffull(); //判断队列满 22 23 bool ifempty(); //判断队列为空 24 25 int alen(); //求当前队列的长度 26 27 int main() 28 29 { 30 31 init(); 33 add(11); 35 add(12); 37 add(13); 39 cout<<out()<<endl; 41 cout<<out()<<endl; 43 cout<<out()<<endl; 45 cout<<out()<<endl; 47 return 0; 49 } 50 53 int alen() 54 55 { 57 return (tail - head +N) % N; 59 } 60 61 bool ifempty() 63 { 65 return head == tail; 67 } 70 71 bool iffull() 73 { 75 return (tail+1) % N == front; 77 } 78 81 int out() 83 { 85 if (ifempty()) 87 { 89 cout<<"队列已空,不能出队"<<endl; 91 return 0; 93 } 94 95 int x = a[head]; 97 head = (head+1) % N; 99 return x; 101 }
105 void add(int x) 107 { 109 if (iffull()) 111 { 113 cout<<"队列已满,不能加入"<<endl; 115 return ; 117 } 119 a[tail] = x; 121 tail = (tail+1) % N; 123 } 127 void init() 128 129 { 131 head =0; 133 tail =0; 135 }

摘自https://blog.csdn.net/noipBar/article/details/84346958

循环队列的基本操作:
1、判断队列空  head == tail
2、入队位置计算 tail=(tail+1)% N  N表示数组元素的长度
3、出队位置计算 head=(head+1)% N
4、判断队列满  (tail+1) % N =tail
5、求队列长度 (tail-head+N) % N
      出队和入队位置计算为以及求队列长度为什么都%N?当head和tail为7时,加1%N=0,就是第一个元素,tail-head<0
也需要+N%N保证位置为正。
循环队列的C++代码实现:
————————————————
版权声明:本文为CSDN博主「noipBar」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/noipBar/article/details/84346958

原文链接: https://www.cnblogs.com/2020cs/p/12250842.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    循环队列的C++实现

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/326549

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午3:52
下一篇 2023年3月1日 下午3:52

相关推荐