题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解析
使用两个栈模拟一个队列,入队先判断栈2是不是空,如果不是空就把元素导入栈1然后向栈1入栈,出队就是把栈1导入栈2然后出栈2的最上面的元素,也要先判断栈2空不空,不空的话可以直接出栈2.
代码
#include <iostream>
#include <stack>
#include <string>
using namespace std;
static stack<int> stack_1;
static stack<int> stack_2;
//把栈1的内容放入到栈2
void Stack1To2()
{
int sum = stack_1.size();
for (int i = 0; i < sum; i++)
{
stack_2.push(stack_1.top());
stack_1.pop();
}
}
//把栈2的内容放入到栈1
void Stack2To1()
{
int sum = stack_2.size();
for (int i = 0; i < sum; i++)
{
stack_1.push(stack_2.top());
stack_2.pop();
}
}
//弹出队头
int poll()
{
int num;
if(stack_2.empty()==true)
Stack1To2();
num = stack_2.top();
stack_2.pop();
return num;
}
//查看队头元素
int peek()
{
int num;
if (stack_2.empty() == true)
Stack1To2();
num = stack_2.top();
return num;
}
int main()
{
int n;
cin >> n;
string s;
for (int i = 0; i < n; i++)
{
cin >> s;
if (s == "peek")
{
cout<<peek()<<endl;
}
else if (s == "poll")
{
poll();
}
else
{
int num;
cin >> num;
if(stack_2.empty()==false)
Stack2To1();
stack_1.push(num);
}
}
return 0;
}