假设以数组Q[M]存放循环队列中的元素,同时设置一个标志tag,以tag==0和tag==1来区分在队头指针(front)和队尾指针(rear)相等时,队列状态是“空”还是“满”。编写与此结构相应的插入(enqueue)和删除(dequeue)算法
完整代码
#include<iostream>
using namespace std;
//创建循环队列
#define MAXQSIZE 50
typedef struct {
int* base;
int front;
int rear;
}SqQueue;
int tag;
//初始化
int InitQueue(SqQueue& Q)
{
Q.base = new int[MAXQSIZE];
if (!Q.base)
exit(OVERFLOW);
Q.front = Q.rear = 0;
tag = 0;
return 1;
}
//入队
int EnQueue(SqQueue& Q,int e)
{
if (Q.rear % MAXQSIZE==Q.front &&tag == 1)
return 0;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
if (Q.front == Q.rear)
tag = 1;
return 1;
}
//出队
int DeQueue(SqQueue& Q, int &e)
{
if (Q.rear % MAXQSIZE==Q.front && tag== 0)
return 0;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
if (Q.rear == Q.front)
tag = 0;
return 1;
}
int main()
{
SqQueue Q;
InitQueue(Q);
EnQueue(Q, 2);
EnQueue(Q, 1);
EnQueue(Q, 3);
EnQueue(Q, 7);
EnQueue(Q, 10);
int n;
for (int i = 0; i <5; i++)
{
DeQueue(Q,n);
cout << n << " ";
}
return 0;
}
输出结果:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)