用两个栈实现队列:最直观的是,一个栈stack1作为入栈,一个栈stack2作为出栈,栈是先进后出,队列是先进先出,所以一个栈无法实现队列,我们需要两个栈来实现,先进后出再先进后出就是先进先出啦。在队列尾部插入整数(push)即直接向stack1中插入元素即可;在队列头部删除整数(pop)即首先判断stack2是否为空,如果不为空则直接从stack2中弹出元素,反之则将stack1中的元素全部弹出来压入stack2中,待到stack1为空时,从stack2中弹出最后一个元素即可,记得要先判断stack2是否为空,这样才不会打乱顺序。
class Solution
{
public:
void push(int node) {
stack1.push(node); //入栈就是直接入栈
}
int pop() {
int node;
if(!stack2.empty())
{
node=stack2.top();
stack2.pop();
}
else
{
while(!stack1.empty())
{
int top=stack1.top();
stack1.pop();
stack2.push(top);
}
node=stack2.top();
stack2.pop();
}
return node;
}
private:
stack<int> stack1; //入栈
stack<int> stack2; //出栈
};
上述代码的pop部分有些冗余,尝试优化一下,注意在刷题中,先尝试逻辑清晰,再尝试优化代码,这样才会理解更加深入~
class Solution
{
public:
void push(int node) {
stack1.push(node); //入栈就是直接入栈
}
int pop() {
int node;
if(stack2.empty())
{
while(!stack1.empty())
{
int top=stack1.top();
stack1.pop();
stack2.push(top);
}
}
node=stack2.top();
stack2.pop();
return node;
}
private:
stack<int> stack1; //入栈
stack<int> stack2; //出栈
};



京公网安备 11010502036488号