牺牲一个存储空间来实现循环队列的队满判断
#include <iostream>
using namespace std;
#define MaxSize 10
#define ElementType int
#define Status bool
#define OK true
typedef struct
{
ElementType *base;
int front;
int rear;
} SqQueue;
Status InitQueue(SqQueue &Q)
{
Q.base = new ElementType[MaxSize + 1];
if (!Q.base)
exit(0);
Q.front = Q.rear = 0;
return OK;
}
Status isEmpty(SqQueue &Q)
{
if (Q.rear != Q.front)
return false;
return OK;
}
ElementType getLength(SqQueue Q)
{
return (MaxSize + Q.rear - Q.front) % MaxSize;
}
Status EnQueue(SqQueue &Q, ElementType e)
{
if ((Q.rear + 1) % MaxSize == Q.front)
return false;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MaxSize;
return OK;
}
Status PopQueue(SqQueue &Q, ElementType &e)
{
if (Q.rear == Q.front)
return false;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return OK;
}
ElementType getQueueTop(SqQueue &Q)
{
if (Q.front != Q.rear)
return Q.base[Q.front];
}
int main()
{
SqQueue Q;
InitQueue(Q);
for (int i = 0; i < 10; i++)
{
if (EnQueue(Q, i))
cout << "入队成功" << i << endl;
else
cout << "入队失败" << endl;
}
cout << "-------------------------------" << endl;
cout << "出栈顺序:" << endl;
while (!isEmpty(Q))
{
int x = 0;
PopQueue(Q, x);
cout << "栈顶元素:" << getQueueTop(Q) << endl;
cout << x << endl;
}
system("pause");
return 0;
}