【剑指offer-解题系列(5)】用两个栈实现队列

来源:互联网 发布:羊毛衣服缩水复原 知乎 编辑:程序博客网 时间:2024/06/07 16:22

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

分析:
当使用push操作时候,push S1。
当使用POp操作时候,pop S2 (  如果S2是空的,就把S1的全部倒入S2,然后pop元素)

代码实现:
stack<int> stack1;
stack<int> stack2;
void push(int node) {
stack1.push(node);
}
int pop() {
int res = 0;
if(!stack2.empty()){
res = stack2.top();
stack2.pop();
}
else{
while(!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
res = stack2.top();
stack2.pop();
}
return res;
}



阅读全文
0 0
原创粉丝点击