题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
思路
一个栈用来存放,另一个栈用来输出,输出的时候注意要将输出栈的全部内容输出完毕后才能填充数据
AC代码
#include <iostream>
#include <stack>
using namespace std;
class Solution
{
public:
void push(int node)
{
stack1.push(node);
}
int pop()
{
while (1)
{
if (!stack2.empty())
{
int y = stack2.top();
stack2.pop();
return y;
}
while (!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main()
{
Solution a;
cout << "11122" << endl;
a.push(1);
a.push(2);
cout << a.pop() << endl;
a.push(3);
cout << a.pop() <<endl;
cout << a.pop() <<endl;
cout << "111" << endl;
return 0;
}
来源:CSDN
作者:chenchenxiaojian
链接:https://blog.csdn.net/weixin_42100456/article/details/103915999