思路比较简单:
- stack1 作为队列的主要的存储,stack2 作为队列操作时的赋值
- pop 时,保证 stack1 中的数据都已经按照出栈的顺序压入到 stack2
- push 的时候,保证 stack2 中数据都已经按照出栈的顺序压入到 stack1
class Solution
{
public:
void push(int node) {
int temp;
while (!stack2.empty()) {
temp = stack2.top();
stack1.push(temp);
stack2.pop();
}
stack1.push(node);
}
int pop() {
int res;
if (stack1.empty() && !stack2.empty()) {
res = stack2.top();
stack2.pop();
return res;
}
int temp;
while (!stack1.empty()) {
temp = stack1.top();
stack2.push(temp);
stack1.pop();
}
res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1; /* valid stack */
stack<int> stack2; /* */
};
京公网安备 11010502036488号