java 中用兩個棧實現一個隊列

/**
 * 思路:左邊A棧,右邊B棧
 * 1.A棧往B棧壓入數據,要一次性把A棧數據一個一個都壓入B棧
 * 2.如果B棧不爲空,A棧絕對不能向B棧壓入數據。
 */

import java.util.Stack;

public class TwoStacksQueue {
    public Stack<Integer> stackPush;
    public Stack<Integer> stackPop;

    public TwoStacksQueue() {
        stackPush = new Stack<Integer>();
        stackPop = new Stack<Integer>();
    }

    //元素進棧
    public void add(int pushInt) {
        stackPush.push(pushInt);
    }

    public int poll() {
        if (stackPop.empty() && stackPush.empty()) {
            throw new RuntimeException("Queue is empty!");
        } else if (stackPop.empty()) {
            while (!stackPush.empty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }
//和poll效果一樣
//    public int peek() {
//        if (stackPop.empty() && stackPush.empty()) {
//            throw new RuntimeException("Queue is empty!");
//        } else if (stackPop.empty()) {
//            while (!stackPush.empty()) {
//                stackPop.push(stackPush.pop());
//            }
//        }
//        return stackPop.peek();
//    }

    public static void main(String[] args) {

        TwoStacksQueue queue = new TwoStacksQueue();
        queue.add(2);
        queue.add(4);
        queue.add(7);
        queue.add(13);
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }
}

結果:
2
4

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