用栈实现队列(每日一道算法题)
2017-11-22 15:17
330 查看
用两个栈实现队列,支持列的基本操作(add,poll,peek)
package stack; import java.util.Stack; /** * @author:MindMrWang *2017年11月14日 *要求:*用两个栈实现队列,支持列的基本操作(add,poll,peek)* *:function:用两个栈实现一个队列 *可以将一个栈设为主栈,另外一个栈设置为传输栈,先将数放入传输栈,然后再将数放入主栈 */ public class twoStacksQueue { private Stack<Integer> stackMain; private Stack<Integer> stackTransfer; public twoStacksQueue() { this.stackMain = new Stack<Integer>(); this.stackTransfer = new Stack<Integer>(); } public int peak() { if(stackMain.isEmpty()&&stackTransfer.isEmpty()) { throw new RuntimeException("your queue is empty"); }else if(stackMain.isEmpty()){ while(!stackTransfer.isEmpty()) { stackMain.push(stackTransfer.pop()); } } return stackMain.peek(); } public int poll() { if(stackMain.isEmpty()&&stackTransfer.isEmpty()) { throw new RuntimeException("your queue is empty"); }else if(stackMain.isEmpty()){ while(!stackTransfer.isEmpty()) { stackMain.push(stackTransfer.pop()); } } return stackMain.pop(); } public void add(int newNum) { this.stackTransfer.push(newNum); } }
相关文章推荐
- 每天一道算法题——用两个栈实现队列和用两个队列实现栈
- 用一个栈实现另一个栈的排序(每日一道算法题)
- 每日一题(33)——用两个栈实现一个队列的功能?要求给出算法和思路
- 每日一道算法题:编程实现两个数的除法,当然不能用除法操作符
- 每天一道算法题——用栈实现队列
- 实现能够返回最小值元素的栈(每日一道算法题)
- 堆实现优先级队列(算法导论第六章)
- 经典算法题每日演练——第十九题 双端队列
- [剑指offer]算法5 两个栈实现1个队列
- 关于一道面试题,使用C#实现字符串反转算法
- 删除链表的倒数第K个节点(每日一道算法题)
- 面试算法——2.双栈实现队列
- 九章算法面试题50 队列上实现Min函数
- 每日一道算法题——1
- C++最大堆实现priority_queue优先级队列(算法导论)
- 算法笔记(堆实现的最大优先队列)
- 每天一道算法题(六)深度优先算法(DFS)学习及Java实现
- uva 11354最小生成树瓶颈路(lca算法实现)(rmq在多校二中有一道题)
- 一道微软公司的面试题目的算法实现
- 每日一道算法题(7)