《剑指offer》09 “用两个栈实现队列”(c++)
原版
class Solution {
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if (stack2.size() <= 0) {
while (stack1.size() > 0) {
int temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
}
//if(stack2.size()==0)
// throw new exception("queue is empty");
int res = stack2.top();
stack2.pop();
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
对上一方法的改进
int pop() {
//利用s.empty()
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top()); //直接push s.top()
stack1.pop();
}
}
int res = stack2.top();
stack2.pop();
return res;
}