附加判定标志的循环队列的基本操作
描述
假设以数组Q[m]存放循环队列中的元素, 同时设置一个标志tag,以tag== 0和tag == 1来区别在队头指针(front)和队尾指针(rear)相等时,队列状态为“空”还是“满”。试编写与此结构相应的插入(enqueue)和删除(dlqueue)算法。
输入
多组数据,每组数据有两行。第一行为一个整数n,n表示入队序列A的长度(n个数依次连续入队,中间没有出队的情况),第二行为序列A(空格分隔的n个整数)。当n=0时,输入结束。
输出
对应每组数据输出一行。依次输出队列中所有的整数,每两个整数之间用空格分隔。
输入样例 1
4 1 2 3 4 5 1 2 4 5 3 0
输出样例 1
1 2 3 4 1 2 4 5 3
#include<iostream>
using namespace std;
#define Maxsize 50
typedef struct Queue {
int Q[Maxsize];
int front;
int rear;
int tag;
};
void Create(Queue& q) {
q.front = q.rear = 0;
q.tag = 0;
}
void EnQueue(Queue& q,int e) {
if (q.front == q.rear && q.tag == 1) {
return;
}
q.Q[q.rear] = e;
q.rear = (q.rear + 1) % Maxsize;
if (q.front == q.rear) {
q.tag = 1;
}
}
void DeQueue(Queue& q) {
if (q.front == q.rear && q.tag == 0) {
return;
}
q.front = (q.front + 1) % Maxsize;
if (q.front == q.rear) {
q.tag = 0;
}
}
int main() {
int n;
while (1) {
cin >> n;
if (n == 0) {
break;
}
Queue q1;
Create(q1);
for (int i = 0; i < n; i++) {
int a;
cin >> a;
EnQueue(q1, a);
}
for (int i = 0; i < n; i++) {
if (i != n - 1) {
cout << q1.Q[i] << " ";
}
else {
cout << q1.Q[i] << endl;
}
}
}
}