java---用两个栈实现队列&&用两个队列实现栈
2015-11-06 11:03
525 查看
(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();的原因在:/article/11216714.html 。
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; } }
相关文章推荐
- spring单元测试使用
- Java代码性能优化总结 推荐收藏
- Java for Web学习笔记(三):Servlet(1)Maven
- struts2中改变struts.xml默认路径或可能遇到的问题
- 0000006_java学习之路_JAVA日期处理
- 如何修正“must override a superclass method”错误。
- eclipse中 快捷键大全
- JAVA中的接口和抽象类
- java nio 抛出NonWritableChannelException异常
- Java通过axis调用WebService
- 关于Mybits3和Spring4的整合
- maven + springmvc + mybatis + ehcache 搭建
- 使用IntelliJ IDEA 14和Maven创建java web项目
- java的重载、覆盖和隐藏的区别
- Spring Hello World 实例
- A fatal error has been detected by the Java Runtime Environment(jdk 1.6的一个BUG)
- JConsole的使用手册 JDK1.5(转)
- eclipse中ant不能智能提示
- spring中@Autowired注解、@Resource注解的区别,以及@Qualifier的使用
- jsonp调用及后台java返回