标签:style blog io os ar for sp 文件 2014
这个思路实在太难想了。。。。
/* *str为PUSH,通过s1.push()使元素入栈; *str为POP时,s2非空,输出栈顶元素,s2.pop()弹出栈顶元素;若s2弹出元素后为空且s1不空,将s1中所有元素push进s2; *str为POP时,s2为空,若s1不空,将s1中所有元素push进s2,最后输出栈顶元素并通过<span style="font-family: Arial, Helvetica, sans-serif;">s2.pop()弹出栈顶元素</span>; */题目描述:用两个栈来实现一个队列,完成队列的Push和Pop操作。
#include<iostream>
#include<string>
#include<stack>
using namespace std;
/*
*str为PUSH,s1.push();
*str为POP时,s2非空,输出栈顶元素s2.pop();若s2弹出元素后为空,若s1不空,将s1中所有元素push进s2;
*str为POP时,s2为空,若s1不空,将s1中所有元素push进s2,最后输出栈顶元素;
*/
int main()
{
int n;
while(cin>>n)
{
stack<int>s1,s2;
int num;
string str;
for(int i=0;i<n;i++)
{
cin>>str;
if(str=="PUSH")
{
cin>>num;
s1.push(num);
}else if(str=="POP")
{
if(!s2.empty())
{
cout<<s2.top()<<endl;
s2.pop();
if(s2.empty())
{
if(!s1.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
}
}else
{
if(s1.empty())
{cout<<-1<<endl;continue;}
else
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
cout<<s2.top()<<endl;
s2.pop();
}
}
}
}
}
/**************************************************************
Problem: 1512
User: hndxztf
Language: C++
Result: Accepted
Time:580 ms
Memory:1656 kb
****************************************************************/标签:style blog io os ar for sp 文件 2014
原文地址:http://blog.csdn.net/mnmlist/article/details/40187861