题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
class Solution //运用两个栈串行使用就可达到队列的效果
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()) //判断,只有当stack2里元素为空时,才从栈1中取元素
{
while(!stack1.empty()) //将栈1中元素取完
{
stack2.push(stack1.top());
stack1.pop();
}
}
int a=stack2.top();
stack2.pop();
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()) //判断,只有当stack2里元素为空时,才从栈1中取元素
{
while(!stack1.empty()) //将栈1中元素取完
{
stack2.push(stack1.top());
stack1.pop();
}
}
int a=stack2.top();
stack2.pop();
return a;
}
private:
stack<int> stack1;
stack<int> stack2;
};