两个栈实现一个队列
2017-11-02 17:04
176 查看
/** * 编写一个类,要求两个栈实现一个队列,并且重写add、poll、peek * @author yyq * */ public class StackQueueDemo { private Stack<Integer> stackPush = new Stack<>(); private Stack<Integer> stackPop = new Stack<>(); public void add(Integer data){ this.stackPush.push(data); } public Integer poll(){ if(stackPush.isEmpty()){ throw new RuntimeException("stack is empty"); } if(stackPush.isEmpty()){ while(!stackPush.isEmpty()){ stackPop.push(stackPush.pop()); } } Integer value = stackPop.pop(); while(!stackPop.isEmpty()){ stackPush.push(stackPop.pop()); } return value; } public Integer peek(){ if(stackPush.isEmpty()){ throw new RuntimeException("stack is empty"); } if(stackPop.isEmpty()){ while(!stackPush.isEmpty()){ stackPop.push(stackPush.pop()); } } Integer value = stackPop.peek(); while(!stackPop.isEmpty()){ stackPush.push(stackPop.pop()); } return value; } }
相关文章推荐
- 使用两个队列实现一个栈
- 用两个队列实现一个栈
- 如何用两个栈实现一个队列,以及用两个队列实现一个栈
- 用两个栈实现一个队列——我作为面试官的小结
- 两个栈实现一个队列
- 用两个栈实现一个队列——我作为面试官的小结
- 用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现一个栈
- 使用两个队列实现一个栈
- 用两个栈实现一个队列的功能
- 程序员面试金典: 9.3栈与队列 3.5实现一个MyQueue类,该类用两个栈来实现一个队列
- 两个栈实现一个队列 && 两个队列实现一个栈
- 两个栈来实现一个队列 《剑指Offer》
- 用两个栈实现一个队列的功能
- 用两个栈实现一个队列
- 使用两个队列实现一个栈,使用两个栈实现一个队列!
- 两个栈实现一个队列的功能
- 两个队列实现一个栈
- 两个栈实现一个队列
- 用两个队列模拟实现一个栈的过程