java---用两个栈实现队列&&用两个队列实现栈
来源:互联网 发布:淘宝号信誉度查询 编辑:程序博客网 时间:2024/05/17 07:36
(1)用两个栈实现队列
Java代码
public class QueueImplementByTwoStacks<E> { private Stack<E> stack1;//专门用来入队 private Stack<E> stack2;//专门用来出队 //队列初始化 QueueImplementByTwoStacks() { stack1 = new Stack<E>(); stack2 = new Stack<E>(); } public int theSize(){return stack1.size()+stack2.size();} public void appendTail(E e){ stack1.add(e);} public E deleteHead() throws Exception{ //move stack1 to stack2 if(stack2.isEmpty()){ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } } if(stack2.isEmpty()){throw new Exception("Queue is empty!");} return stack2.pop(); }}
(2)用两个队列实现栈
java 代码
注释:pop()方法中的return element;不能写成return queue1.poll();的原因在:http://blog.csdn.net/hungry_bug/article/details/49689637 。
import java.util.PriorityQueue;import java.util.Queue;public class StackImplementByTwoQueues <E>{ private PriorityQueue<E> queue1 = new PriorityQueue<>(); private PriorityQueue<E> queue2= new PriorityQueue<>(); private int size;//因为java中的Queue是一个接口interface不是一个类class,所以不能创建对象,可以直接拿来使用。// StackImplementByTwoQueues (){// queue1 = new Queue();// queue2 = new Queue();// } public int theSize(){ return size; } public boolean isEmpty(){return size==0;} //入栈 public void push(E e){ queue1.add(e); size++; } /** * 出栈有两种思路: 思路(1):每次拷贝都是将源队列中的全部元素拷贝到目的队列中去,只由一个队列(队列1或者队列2)实现出栈。 * 思路(2):每次拷贝结束后,源队列都留有最后一个元素,用于出栈。 *//* //出栈方法1:思路(1) public E pop(){ //1.先将队列1中的前queue1.size()-1个元素压入队列2中 int queue1_Length = queue1.size();//先保存长度,因为队列元素在拷贝时,发生变化。循环的次数也在变化而产生错误。 for(int i=0;i<queue1_Length-1;i++) { E e = queue1.poll();//删除队头的元素,并返回。 queue2.add(e); } //2.保存队列1中的最后一个元素 E element = queue1.poll(); //3.再将队列2中的所有元素压入队列1中。 int queeu2_Length = queue2.size(); for(int j =0;j<queeu2_Length;j++){queue1.add(queue2.poll());} size--; return element; }*/ //出栈方法2:思路(2) public E pop(){ E element = null; if(!queue1.isEmpty()&&queue2.isEmpty()){ //1.将队列1中除最后一个元素之外的全部元素压入队列2中。 int queue1_Length = queue1.size();//先保存长度,因为队列元素在拷贝时,发生变化。循环的次数也在变化而产生错误。 for(int i=0;i<queue1_Length-1;i++) { E e = queue1.poll();//删除队头的元素,并返回。 queue2.add(e); } //2.保存队列1中的最后一个元素 element = queue1.poll(); } else if(queue1.isEmpty()&&!queue2.isEmpty()){ //1.再将队列2中除最后一个元素之外的全部元素压入队列1中。 int queeu2_Length = queue2.size(); for(int j =0;j<queeu2_Length-1;j++){queue1.add(queue2.poll());} //2.保存队列2中的最后一个元素 element = queue2.poll(); } size--; return element; }}
0 0
- 用两个栈实现队列java实现
- 用两个栈实现队列 & 用两个队列实现栈
- 用两个队列实现栈&用两个栈实现队列
- 用两个栈实现队列 & 两个队列实现一个栈
- 两个栈实现队列&&用两个队列实现一个栈
- 用两个栈实现队列 & 两个队列实现栈
- java 用两个栈实现队列
- java用两个队列实现栈
- java-用两个栈实现一个队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个栈实现队列
- 用两个队列实现栈
- 用两个栈实现队列
- 用两个队列实现栈
- 学习笔记—二叉树中求度为2的节点个数
- Mysql日期函数使用汇总
- Java反射知识点总结
- 【SSH项目实战】国税协同平台-17.权限鉴定&解决登录嵌套
- MySql中having字句对组记录进行筛选使用说明
- java---用两个栈实现队列&&用两个队列实现栈
- 国嵌嵌入式学习笔记之学习方法
- Java代码复用
- Summary Before NOIP
- 非互质中国剩余定理求线形模方程组(形如 X%mi=ai)
- 动态设置android:drawableLeft|Right|Top|Bottom
- #define的用法与注意事项
- 安卓 微信开发步骤
- Ubuntu 1404 安装 qq