#include<iostream>
using namespace std;
//tag为0时,front=rear即为队空
//一开始,在满的时候,没有考虑到front==rear的情况,导致输出不出来
//在队列满的时候,求长度有问题啊
//(Q.rear - Q.front + MAXSIZE) % MAXSIZE;
//在tag标志位时,不能用这个常规方法求长度,队满的时候会检测为0,需要单独判断
#define MAXSIZE 3
typedef struct {
int data[MAXSIZE];
int front, rear;
int tag;
}Queue;
void initQueue(Queue& Q) {
Q.front = Q.rear = 0;
Q.tag = 0;
}
bool enQueue(Queue& Q,int e) {
if (Q.front == Q.rear && Q.tag == 1)
return false;
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;
Q.tag = 1;
return true;
}
bool deQueue(Queue& Q,int &e) {
if (Q.front == Q.rear && Q.tag == 0)
return false;
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
Q.tag = 0;
return true;
}
int getlength(Queue Q) {
if ((Q.rear + MAXSIZE - Q.front) % MAXSIZE == 0 && Q.tag == 1)
return MAXSIZE;
return (Q.rear + MAXSIZE - Q.front ) % MAXSIZE;
}
void printf(Queue Q) {
if (Q.front == Q.rear && Q.tag == 0)
return;
int a = Q.front;
for (int i = 0; i<getlength(Q) ; i++)
cout << Q.data[a+i] << " ";
cout << endl;
}
bool empty(Queue Q) {
if (Q.front == Q.rear && Q.tag == 0)
return true;
else
return false;
}
int main() {
Queue Q;
int len;
initQueue(Q);
if (empty(Q))
cout << "空" << endl;
enQueue(Q, 1);
enQueue(Q, 2);
enQueue(Q, 3);
printf(Q);
len = getlength(Q);
cout << "len:" << len << endl;
int a;
deQueue(Q, a);
cout << a << endl;
printf(Q);
len = getlength(Q);
cout << "len:" << len << endl;
return 0;
}
04-19
722
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-03
366
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-20
791
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-18
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交