两个栈模拟队列
- 入队:将元素进栈A。
- 出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;如果不为空,栈B直接出栈。
C/C++代码
class Solution
{
public:
void push(int node) { //入队
stack1.push(node);
}
int pop() { //出队
int a;
if(stack2.empty()){
while(!stack1.empty()){
a = stack1.top();
stack2.push(a);
stack1.pop();
}
}
a = stack2.top();
stack2.pop();
return a;
}