题目描述
After the make-up examine,Tiantian is bored because he needn’t review digital circuit now.So he decides to calculate the number of people in the queue.What a boring boy!
There are three operations of the queue:
In x: push x(x <= 10000) in the end of the queue.
Out: write out the first element of the queue and erase it.If the queue is empty,write out -1.
Count: return the length of the queue.
输入描述
Each test contains a single number N(N <= 1000) means the number of operations.Following n lines describe the operation of the queue.
输出描述
For each Out and Count operation,write out its expected answer.
样例输入
10
Count
Count
In 9035
Out
Out
In 9809
In 4983
Out
Count
Out
样例输出
0
0
9035
-1
9809
1
4983
能过评测就行的答案
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
class Queue{
public:
int Count=0;
//stack<int> a,b;
int a[1000];
int index=0;
int tail=0;
void In(int number){
++Count;
a[tail]=number;
++tail;
}
void Out(){
if(Count==0){
cout<<"-1"<<endl;
}
else{
--Count;
cout<<a[index]<<endl;
++index;
}
}
};
int main(){
Queue Q;
int num;
cin>>num;
for (int i = 0; i < num; i++)
{
string tmp;
cin>>tmp;
if(tmp=="Count"){
cout<<Q.Count<<endl;
}
else if(tmp=="In"){
int temp;
cin>>temp;
Q.In(temp);
}
else if(tmp=="Out"){
Q.Out();
}
}
}
Yizuodi的答案
#include <iostream>
#include <stack>
using namespace std;
class Queue{
private:
stack<int> a,b;
public:
void push(int number){
a.push(number);
}
void pop(){
if(!b.empty()){
cout<<b.top()<<endl;
b.pop();
}
else if(!a.empty()){
while(!a.empty()){
b.push(a.top());
a.pop();
}
cout<<b.top()<<endl;
b.pop();
}
else{
cout<<"-1"<<endl;
}
}
int count()const{
return a.size()+b.size();
}
};
int main(){
Queue Q;
int num;
cin>>num;
for (int i = 0; i < num; i++)
{
string tmp;
cin>>tmp;
if(tmp=="Count"){
cout<<Q.count()<<endl;
}
else if(tmp=="In"){
int temp;
cin>>temp;
Q.push(temp);
}
else if(tmp=="Out"){
Q.pop();
}
}
}