JZ5 用两个栈实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
两个栈:stack1,stack2
push操作:往stack2中放数据;
pop操作:从stack1中取数据,如果stack1中是空的,那么先把stack2中的数据全部依次弹出存到stack1中,再取数据
注意:对于栈的top操作,只是取第一个元素,并没有进行弹出,所以每次取完后需要进行pop弹出
代码
class Solution
{
public:
void push(int node) {
stack2.push(node);
}
int pop() {
int res=0;
if(!stack1.empty())
{
res = stack1.top();
stack1.pop();
}
else
{
while(!stack2.empty())
{
stack1.push(stack2.top());
stack2.pop();
}
res=stack1.top();
stack1.pop();
}
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
