JZ9 用两个栈实现队列


class Solution
{
public:
//用两个栈实现 队列 栈是先进后出,队列是先进先出
//在队列尾部插入整数
void push(int node) {
//入队就正常入栈
stack1.push(node);
}
//在队列头部删除整数,先进先出
int pop() {
//将第一个栈中内容弹出放入第二个栈中
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
//第二个栈栈顶就是最先进来的元素,即队首
int res = stack2.top();
stack2.pop();
//再将第二个栈的元素放回第一个栈
//这样使得第一个栈中虽然取得了最里面的元素,但是顺序并没有改变
while(!stack2.empty())
{
stack1.push(stack2.top());
stack2.pop();
}
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};

浙公网安备 33010602011771号