剑指offer_栈和队列---用两个栈实现一个队列
2017-08-22 10:38
447 查看
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。解题思路
1,用stack1来充当入队,将stack1所有元素出栈到stack2,然后stack2出栈,实现先进先出。2,三种算法,一种比一种优化
/** * */ package 栈和队列; import java.util.Stack; /** * <p> * Title:StacktoQueue * </p> * <p> * Description: * </p> * * @author 田茂林 * @data 2017年8月22日 上午10:16:19 */ public class StacktoQueue { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); //==================================================普通方法=============================== public void push(int node) { stack1.push(node); } public int pop() { while(!stack1.isEmpty()){ stack2.push(stack1.pop()); //把stack1的所有元素入栈到2 } int num = stack2.pop(); //返回值为2出栈 while(!stack2.isEmpty()){ stack1.push(stack2.pop()); //把2中所有元素重新放回到1 } return num; //操作数过多 } //==================================================优化=============================== public void push1(int node) { stack1.push(node); } public int pop1() { while(stack1.size()>1){ stack2.push(stack1.pop()); //栈1里只剩一个元素,用于出栈 } int num = stack1.pop(); //栈1出栈 while(!stack2.isEmpty()){ //把剩下的元素重新放回栈1 stack1.push(stack2.pop()); } return num; } //==================================================更加优化=============================== public void push2(int node) { stack1.push(node); } public int pop2() { if(stack1.isEmpty()&&stack2.isEmpty()) throw new RuntimeException("queue is empty"); if(stack2.isEmpty()){ //只有栈2空的时候才把栈1的放进去,这样避免了频繁的操作 while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); d862 } public static void main(String[] args) { // TODO Auto-dgenerated method stub } }
相关文章推荐
- 剑指offer-用两个栈实现一个队列
- 【剑指Offer】两个栈实现一个队列
- 【剑指offer】用两个栈实现一个队列,用两个队列实现一个栈
- 剑指offer--两个栈实现一个队列
- 剑指offer--两个栈实现一个队列
- 剑指offer-09 用两个栈来实现一个队列
- 剑指offer-两个栈实现一个队列
- 剑指offer 7---使用两个栈实现一个队列
- 剑指offer-用两个栈实现一个队列
- 《剑指 Offer》学习(2)—— 9_两个栈实现一个队列
- 【剑指offer】两个栈实现一个队列
- 剑指offer—编程题7(用两个栈实现一个队列)
- 剑指offer-两个栈实现一个队列
- 【九度OJ1512】|【剑指offer7】用两个栈实现一个队列
- 剑指offer面试题java实现之题7:用两个栈模拟一个队列的入队和出队操作
- 剑指offer之面试题7用两个栈实现一个队列
- 剑指offer----用两个队列实现一个栈(java代码)
- 【剑指Offer】JS实现两个队列表示一个栈
- 【面试题】剑指Offer-7-两个栈实现一个队列
- Python剑指offer之两个栈实现一个队列-两个队列实现一个栈