题目描述
实现一个队列,使其支持push、pop、empty、query操作
算法1
循环队列
模拟了一个循环队列
C++ 代码
#include<iostream>
using namespace std;
const int N = 1e3+10;
int a[N];
int front, tail; //front指向队头元素,用以出队,tail指向队尾元素后面一位,用来入队;
void init(){
front = 0;
tail = 0;
}
void push(int x){
a[tail] = x;
tail = (tail+1)%N;
}
void pop(){
front = (front+1)%N;
}
bool empty(){
return front == tail;
}//如果front和tail指向同一个位置则为空;
bool full(){
return front == (tail+1)%N;
}//如果tail指向front前一个元素则为满;
int query(){
return a[front];
}
int main()
{
int m;
cin>>m;
init();
string op;
int x;
while(m--){
cin>>op;
if(op == "push"){
cin>>x;
push(x);
}else if(op == "empty")
cout<<(empty() ? "YES" : "NO")<<endl;
else if(op == "pop")
pop();
else
cout<<query()<<endl;
}
return 0;
}
算法2
模拟普通队列
C++ 代码
#include<iostream>
using namespace std;
const int N = 1e5+10;
int a[N], head = 0, tail = 0;
int main()
{
int m;
cin>>m;
string op;
int x;
while(m--){
cin>>op;
if(op == "push"){
cin>>x;
a[tail++] = x;
}else if(op == "pop")
++head;
else if(op == "empty")
cout<<(head == tail ? "YES" : "NO")<<endl;
else
cout<<a[head]<<endl;
}
return 0;
}