使用两个栈来模拟序列,关键在于实现他要求的先入先出,所以应该在pop的时候先将stack1中的数依次push入stack2,这样,stack2栈顶的元素就是stack1先输入的数.将其记录下来,然后pop掉,最后再放回stack1中即可.
class Solution {
public:
void push(int node) {
stack1.push(node);
}
int pop() {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
int ans = stack2.top();;
stack2.pop();
while (!stack2.empty()) {
stack1.push(stack2.top());
stack2.pop();
}
return ans;
}
private:
stack<int> stack1;
stack<int> stack2;
};

京公网安备 11010502036488号