mock queue
Algorithm diagram
Algorithm Pseudocode
example
Implement a queue, which is initially empty and supports four operations:
push x
– Insert a number x to the end of the queue;pop
– Pop a number from the head of the queue;empty
– Determine whether the queue is empty;query
– Query the queue head element.
Now there are M operations to be performed on the queue, and each of operation 3 and operation 4 must output a corresponding result.
input format
The first line contains an integer M, representing the number of operations.
Next M lines, each line contains an operation command, and the operation command is one of push x
, pop
, .empty
query
output format
For each empty
and query
operation, a query result is output, and each result occupies one line.
Among them, empty
the query result of the operation is YES
or NO
, and query
the query result of the operation is an integer representing the value of the queue head element.
data range
1≤M≤100000,
1≤x≤109,
all operations are guaranteed to be legal.
Input sample:
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
Sample output:
NO
6
YES
4
Code
#include<iostream>
using namespace std;
const int maxn = 1000001;
int q[maxn],hh,tt=-1;
int main(){
int M,k;
string s;
cin>>M;
while(M --){
cin>>s;
if(s == "push"){
cin>>k;
q[++ tt] = k;
}
else if(s == "pop"){
hh = hh + 1;
}
else if(s == "empty"){
if(hh <= tt){
cout<<"NO"<<endl;
}
else{
cout<<"YES"<<endl;
}
}
else{
cout<<q[hh]<<endl;
}
}
return 0;
}