题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
分析
思路:堆栈A用来入队,堆栈B用于出队。出队则需判将堆栈A的元素依次出栈并加入堆栈B,最后需要出队的元素就在堆栈B的顶端。
github链接如下:JZ05-用两个栈实现队列
C++代码
#include <stack>
class Solution
{
public:
void push(int node) {
this->stack1.push(node);
}
int pop() {
if(this->stack1.empty() && this->stack2.empty()){
return 0;
}
if(this->stack2.empty()){
while(!this->stack1.empty()){
this->stack2.push(this->stack1.top());
this->stack1.pop();
}
}
int top = this->stack2.top();
this->stack2.pop();
return top;
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main(){
return 0;
}