题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路: push的话就直接push到一个栈里,复杂度为O(1),pop的话就把栈里的元素丢进另外一个栈里,然后把栈底的元素pop出来,再把其他元素再重新丢回去,pop一次的复杂度为O(n)。
代码:
class Solution
{
public:
void push(int node) {
//if(stack2)
stack1.push(node);
}
int pop() {
while(stack1.size()>1)
{
int tp = stack1.top();
stack1.pop();
stack2.push(tp);
}
int ans = stack1.top();
stack1.pop();
while(stack2.size())
{
int tp = stack2.top();
stack2.pop();
stack1.push(tp);
}
return ans;
}
private:
stack<int> stack1;
stack<int> stack2;
};