题目描述
用两个栈来实现队列
题目链接
首先介绍下栈和队列,栈是一种先进后出的数据结构,队列是先进先出的数据结构,
想要用两个栈来模拟队列,当每次出队列时先模拟出反转的队列,然后取出栈头如图
然后再把栈2反转回栈1
即完成了队列的操作
代码如下:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while(stack1.size())
{
int x=stack1.top();
stack1.pop();
stack2.push(x);
}
int x=stack2.top();
stack2.pop();
while(stack2.size())
{
int x=stack2.top();
stack2.pop();
stack1.push(x);
}
return x;
}
private:
stack<int> stack1;
stack<int> stack2;
};
京公网安备 11010502036488号