用两个栈实现队列
2018-04-13 20:47
113 查看
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。解析:两个栈,一个入口一个出口。push时正常操作,pop的时候,先pop出口栈的元素,若出口栈为空,则先将所有入口栈的元素移入出口栈中,再pop出口栈。
代码:
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (!stack2.empty()) {
return stack2.pop();
}
while (!stack1.empty()) {
int temp = stack1.pop();
stack2.push(temp);
}
return stack2.pop();
}
代码:
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (!stack2.empty()) {
return stack2.pop();
}
while (!stack1.empty()) {
int temp = stack1.pop();
stack2.push(temp);
}
return stack2.pop();
}
相关文章推荐
- 利用两个栈实现⼀个队列
- 用两个栈实现一个队列功能
- 使用两个栈实现队列的功能
- 用两个队列实现栈
- 如何利用两个队列实现一个栈,如何利用两个栈实现一个队列
- 用两个栈实现队列
- 《剑指Offer》面试题-用两个栈实现队列
- 两个队列实现一个栈
- [剑指offer][面试题07]用两个栈实现队列
- 两个栈实现一个队列及相关类型题
- 面试题之【用两个栈实现队列】
- 用两个栈如何实现队列?
- 【剑指Offer】JS实现两个队列表示一个栈
- 数据结构(栈--两个队列实现)
- 用两个栈实现队列
- 剑指offer:7-用两个栈实现队列
- [LeetCode] Binary Tree Level Order Traversal 与 Binary Tree Zigzag Level Order Traversal,两种按层次遍历树的方式,分别两个队列,两个栈实现
- 两个栈实现队列
- 笔试算法题(12):整数的string到int转换 & 两个栈实现队列
- 剑指:用两个队列实现栈的先进后出