题目1512:用两个栈实现队列

题目描述:

用两个栈来实现一个队列,完成队列的Push和Pop操作。
队列中的元素为int类型。

输入:

每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。

输出:

对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。

样例输入:
3
PUSH 10
POP
POP
样例输出:
10
-1
这题还是挺简单的,开始的时候没有AC主要是因为输出的格式不对,我把要输出的值存在一个vector里,按要求输出就行了。
#include<iostream>
#include<stack>
#include<vector>
#include<string>
using namespace std;
int main()
{
    stack<int > stk1;
    stack<int > stk2;
    int n;
    cin>>n;
    if(n<1||n>100000)
        return 0;
    vector<int > res;
    string str;
    for(int i=0;i<n; i++)
    {
        cin>>str;
        if(str=="PUSH")
        {
            int temp;
            cin>>temp;
            stk1.push(temp);
        }
        else if(str=="POP")    
        {
            if(!stk2.empty())
            {
                int temp=stk2.top();
            //    cout<<temp;
                res.push_back(temp);
                stk2.pop();
            }
            else if(stk1.empty()&&stk2.empty())
            {
                //cout<<-1;
                res.push_back(-1);
            }
            else
            {
                int len=stk1.size();
                while(len)
                {
                  int temp=stk1.top();
                  stk1.pop();
                  stk2.push(temp);
                  len--;
                }
                int temp=stk2.top();
            //    cout<<temp;
                res.push_back(temp);
                stk2.pop();
            }
        }
    }
    for(int i=0;i<res.size();i++)
        cout<<res[i]<<endl;
    return 0;
}
    
原文地址:https://www.cnblogs.com/qiaozhoulin/p/5320190.html