使用stack1作为压入栈,使用stack2作为弹出栈;
压入时直接压入stack1,弹出时判断stack2是否为空,如果为空,证明队列头元素在stack1的底部,则依次将stack1中的元素压入stack2中;如果不为空,证明对头元素仍然在stack2的上层,直接弹出stack2中元素即可
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()) {
while(stack1.size()) {
int x = stack1.top();
stack1.pop();
stack2.push(x);
}
}
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1; // 压入栈
stack<int> stack2; // 弹出栈
};
京公网安备 11010502036488号