剑指offer-刷题笔记-简单题-JZ9 用两个栈实现队列
比较好实现,就是要注意一点,如果stack2中有元素,此时一定要先把stack2中元素pop,然后再将stack1中元素压入stack2中,最后要优化代码,把同样条件的放到一起
题解1
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int result;
if(!stack2.empty())
{
result = stack2.top();
stack2.pop();
return result;
}
while(!stack1.empty()){
int value;
value = stack1.top();
stack2.push(value);
stack1.pop();
}
result = stack2.top();
stack2.pop();
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};
题解2-整合版本
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int result;
if(stack2.empty())
{
while(!stack1.empty()){
int value;
value = stack1.top();
stack2.push(value);
stack1.pop();
}
}
result = stack2.top();
stack2.pop();
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};