栈和队列——由两个栈组成的队列
来源:互联网 发布:编程类书籍在哪找 编辑:程序博客网 时间:2024/05/18 00:42
【题目】
编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)
【代码实现】
import java.util.Stack;class TwoStacksQueue{ public Stack<Integer> stackPush; public Stack<Integer> stackPop; public TwoStacksQueue(){ stackPush = new Stack<Integer>(); stackPop = new Stack<Integer>(); } public void add(int pushInt) { stackPush.push(pushInt); } public int poll(){ if(stackPop.empty() && stackPush.empty()){ throw new RuntimeException("Queue is empty."); }else if(stackPop.empty()){ while(!stackPush.empty()){ stackPop.push(stackPush.pop()); } } return stackPop.pop(); } public int peek(){ if(stackPop.empty() && stackPush.empty()){ throw new RuntimeException("Queue is empty."); }else if(stackPop.empty()){ while(!stackPush.empty()){ stackPop.push(stackPush.pop()); } } return stackPop.peek(); }}
阅读全文
2 0
- 栈和队列 由两个栈组成的队列
- 栈和队列——由两个栈组成的队列
- 由两个栈组成队列
- 设计由两个栈组成的队列
- 2.由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 由两个栈组成的队列
- 1栈和队列--由两个栈组成队列
- 栈和队列---由两个栈组成队列
- 栈和队列(2)--由两个栈组成的队列
- (一)栈和队列--由两个栈组成的队列 java实现
- 【栈】由两个栈组成队列
- 【WG面试算法】由两个栈组成的队列
- 1_2由两个栈组成的队列
- 4999: This Problem Is Too Simple!
- [PAT甲级]1017. Queueing at Bank (25)(银行办理业务平均等待时间)
- Java编程思想-4
- Windows的消息队列与消息循环
- 视差滚动2
- 栈和队列——由两个栈组成的队列
- centos 日志文件
- 正则表达式
- Kostya the Sculptor CodeForces
- 固定页面背景
- 文章标题
- x264编解码个人简识
- Spring(二):了解IOC
- qduoj ycb的ACM进阶之路(多重背包)