题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
一个水题,不过有一个坑:我们假设stack1是输入用的,stack2是输出用的,必须是stack2是空的时候才能把所有stack1的数据放入stack2中!
AC代码
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()) {
while(!stack1.empty()) {
auto t = stack1.top();
stack1.pop();
stack2.push(t);
}
}
auto t = stack2.top();
stack2.pop();
return t;
}
private:
stack<int> stack1;
stack<int> stack2;
};
// 下面是测试用的
int main() {
Solution so;
so.push(1);
so.push(2);
so.push(3);
cout << so.pop() << " ";
cout << so.pop() << " ";
so.push(4);
cout << so.pop() << " ";
so.push(5);
cout << so.pop() << " ";
cout << so.pop() << " ";
return 0;
}