zoukankan      html  css  js  c++  java
  • 《剑指offer》面试题7 用两个栈实现队列 Java版

    书中方法:队列是先进先出的,栈是先进后出的,试想把一串数压入A栈,接着一个个出栈并压入B栈,便会完成“头在下”到“头在上”的转变。B栈内还有元素时,直接出栈表示出列,如果没有元素则将A栈内元素压入B栈内。这个没有测试,省略了异常抛出。

    public class QueueImplementionByTwoStack<Integer> {
    	private Stack<Integer> in = new Stack<>();
    	private Stack<Integer> sup = new Stack<>();
    	
    	public void offer(Integer a){
    		in.push(a);
    	}
    	
    	public Integer poll(){
    		if(sup.isEmpty()){
    			while(!in.isEmpty()){
    				sup.push(in.pop());
    			}
    		}
    		return sup.pop();
    	}
    }
    

    题目7扩展:用两个队列实现实现栈

    书中方法:由于用两个队列并不能改变元素的出列顺序(而用两个栈可以),在表示出栈的时候,我们只能把前面的元素移入另一个队列,然后在原队列获得这个元素。也就是说有一个队列始终作为辅助,临时存放需要pop出的元素的前面的元素。

    public class StackImplementionByTwoQueue<Item> {
    	private LinkedList<Item> q1;
    	private LinkedList<Item> q2;
    	
    	public void push(Item item){
    		if(q1.isEmpty()){
    			q2.offer(item);
    		}else q1.offer(item);
    	}
    	
    	public Item pop(){
    		if (q2.isEmpty()) {
    			while(q1.size()>1){
    				q2.offer(q1.poll());
    			}
    			return q1.poll();
    		}else{
    			while(q2.size()>1){
    				q1.offer(q2.poll());
    			}
    			return q2.poll();
    		}
    	}
    	
    }
    
  • 相关阅读:
    poj 1511Invitation Cards
    hust 1608Dating With Girls
    sdibt 2128Problem A:Convolution Codes
    hdu 1325Is It A Tree?
    poj 2240Arbitrage
    hdu 2818Building Block
    poj 1789Truck History
    poj 1125Stockbroker Grapevine
    展望未来
    告别过去
  • 原文地址:https://www.cnblogs.com/czjk/p/11611096.html
Copyright © 2011-2022 走看看