劍指Offer學習-面試題9:用兩個棧實現隊列

	/**
     * 兩個棧實現一個隊列
     * 讓添加的元素進入輸入棧,彈出的時候先把輸入棧裏面的元素加入輸出棧,然後從輸出棧裏面彈出元素。
     */
    public class Queue {

        private Stack<Integer> input = null;
        private Stack<Integer> output = null;

        public Queue() {
            input = new Stack<>();
            output = new Stack<>();
        }

        public void add(int val) {
            input.add(val);
        }

        public int pop() {
            if (!output.isEmpty())
                return output.pop();

            while (!input.isEmpty())
                output.add(input.pop());

            if (!output.isEmpty())
                return output.pop();

            return -1;
        }

    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章