#include<iostream>
using namespace std;
#define Ok 1
#define Error 0
#define Overflow -1
#define Maxsize 100
typedef struct
{
int *base; //存储空间基地址
int front; //头指针,每次在队头删除元素,front加1
int rear; //尾指针,每次在队尾插入元素,rear 加1
int queuesize;
} SqQueue;
//初始化
int Init_Queue(SqQueue &Q)
{
//构造一个最大存储空间为MaxSize的空循环队列Q
Q.base = new int[Maxsize];
if(!Q.base) //存储分配失败
exit(Overflow);
Q.queuesize = Maxsize;
Q.front = Q.rear = 0; //头尾指针置为0,对列为空
return Ok;
}
//求队列长
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + Maxsize) % Maxsize;
}
//入队
int EnQueue(SqQueue &Q, int e)
{
if((Q.rear + 1) % Q.queuesize == Q.front)
return Error; //队满
Q.base[Q.rear] = e; //保存队头元素
Q.rear = (Q.rear + 1) % Q.queuesize; //队头指针加1
return Ok;
}
//出对
int DeQueue(SqQueue &Q)
{
if(Q.front == Q.rear) //队空
return Error;
Q.front = (Q.front + 1) % Q.queuesize;
return Ok;
}
//取队头元素
int GetHead(SqQueue Q)
{
if (Q.front != Q.rear) //队非空
{
return Q.base[Q.front]; //返回队头元素的值,队头指针不变
}
}
//输出
void printqueue(SqQueue Q)
{
while(Q.front != Q.rear)
{
cout << GetHead(Q) << " ";
Q.front = (Q.front + 1) % Q.queuesize;
//DeQueue(Q);
}
cout << endl;
}
int main()
{
SqQueue q;
Init_Queue(q);
cout << "请输入数字:(0-3):0--退出,1--求表长,2--DeQue,3--EnQue\n";
for (int i = 0; i < 10; ++i)
EnQueue(q, i);
int c, d;
for(int i = 0; i < 4; ++i)
{
cin >> c;
if(c == 1)
cout << QueueLength(q) << endl;
else if(c == 2)
{
cout << "yuan:";
printqueue(q);
DeQueue(q);
cout << "DE hou:";
printqueue(q);
cout << "Len=: " << QueueLength(q) << endl;
}
else if(c == 3)
{
cout << "yuan:";
printqueue(q);
cout << "input num:";
cin >> d;
EnQueue(q, d);
cout << "En hou:";
printqueue(q);
cout << "Len=: " << QueueLength(q) << endl;
}
else if(c == 0)
{
return 0;
}
}
return 0;
}
数据结构期末复习(さん)--循环队列定义及使用
最新推荐文章于 2022-10-07 16:57:03 发布