两个栈来回倒腾即可,结点先直接丢进stack1,当stack2为空时,将stack1所有的结点都丢进去,弹出stack2的节点。
class Solution
{
public:
void push(int node) {
stack1.emplace(node);
}
int pop() {
if(stack2.empty()){
while(!stack1.empty()){
int x=stack1.top();
stack1.pop();
stack2.emplace(x);
}
}
int x=stack2.top();
stack2.pop();
return x;
}
private:
stack<int> stack1;
stack<int> stack2;
};

京公网安备 11010502036488号