队列的数组实现
程序员文章站
2022-07-14 13:57:40
...
//队列的数组实现
//入队(ENQUEUE)时检查队列上溢,出队(DEQUEUE)时检查队列下溢
//head指向队头元素,tail指向队尾下一个新元素将要插入的位置
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#define N 1000
using namespace std;
int head,tail;
int Q[N];
void ENQUEUE(int Q[],int &head,int &tail, int x)
{
if(((tail+1)%N) == head)
{
cout << "overflow" <<endl;
return;
}
else
{
Q[tail]=x;
tail=(tail+1)%N;
}
}
int DEQUEUE(int Q[],int &head,int &tail)
{
if(head == tail)
{
cout << "underflow" <<endl;
return 0;
}
else
{
int temp=Q[head];
head = (head+1)%N;
return temp;
}
}
int main(int argc, char *argv[])
{
int a;
while(1)
{
cout << "1 : ENQUEUE" << endl;
cout << "2 : DEQUEUE" << endl;
cout << "0 : QUIT" << endl;
cin >> a;
if(a == 0) return 0;
while(a)
{
if((a != 1) && (a != 2))
{
cout << "INPUT WRONG" <<endl;
return 0;
}
if(a == 1)
{
system("cls");
cout << "input x" <<endl;
int x; cin >> x;
ENQUEUE(Q,head,tail,x);
system("cls");
break;
}
if(a == 2)
{
system("cls");
cout << DEQUEUE(Q,head,tail) << endl;
break;
}
}
}
return 0;
}
上一篇: 队列的数组实现
下一篇: 队列(一)——队列的数组实现方式