劍指offer面試題java實現之題7之相關題目:用兩個隊列實現一個棧

/**
 * 使用兩個隊列模擬棧操作
 * @author Administrator
 *
 */
public class StackWithTwoQueue<T> {
    Queue<T> queue1 = new LinkedList<T>();
    Queue<T> queue2 = new LinkedList<T>();
    /**
     *模擬入棧操作
     */
    public void push(T t){
        if(queue1.size()>0)
            queue1.add(t);
        else
            queue2.add(t);
    }
    /**
     * 模擬出棧操作
     * @return
     */
    public T pop(){
        /*選擇不爲空的那個隊列,然後將所有元素(除隊尾元素外),
         * 移動到另一個隊列中,接着進行出棧操作
         * */
        if(queue1.size()>queue2.size()){
            while(queue1.size()!=1){
                queue2.add(queue1.remove());
            }
            return queue1.remove();//出棧操作
        }else if(queue2.size()>queue1.size()){
            while(queue2.size()!=1){
                queue1.add(queue2.remove());
            }
            return queue2.remove();//出棧操作
        }else{//此情況爲兩個隊列全部爲空
            try {
                throw new Exception("棧爲空,不能出棧");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    public static void main(String[] args) {
    StackWithTwoQueue<Integer> stack = new StackWithTwoQueue<Integer>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        System.out.println(stack.pop());
        stack.push(4);
        stack.push(5);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章