两个栈stack1,stack2,入队时压入stack1,出队时将stack1中的元素弹出压入stack2中,此时元素恢复原来顺序,将stack2栈顶弹出,完成出队(当stack2不为空时直接弹出stack2栈顶元素)。
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int a;
if(stack2.empty()){
while(!stack1.empty()){
a=stack1.top();
stack2.push(a);
stack1.pop();
}
}
a=stack2.top();
stack2.pop();
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};