java使用棧實現隊列

/**
 * 使用棧實現隊列
 * 思路:使用兩個棧,加入元素是將值保存到棧A中,取出時將A的值全部放到B中,從B中出棧
 * 時間複雜度:均攤時間複雜度爲O(1)
 */
public class StackQueue {

    private Stack<Integer> stackA = new Stack<>();
    private Stack<Integer> stackB = new Stack<>();

    /**
     * 入隊列
     * @param data
     */
    public void enQueue(Integer data){
        stackA.push(data);
    }

    /**
     * 取出元素
     * @return
     */
    public Integer deQueue(){
        if(stackB.isEmpty()){
            if(stackA.isEmpty()) {
                return null;
            }
            transfer();
        }
        return stackB.pop();
    }

    /**
     * 將棧A中的元素的值移到B棧中
     */
    private void transfer(){
        while (!stackA.isEmpty()) {
            stackB.push(stackA.pop());
        }
    }

    public static void main(String[] args) {
        StackQueue stackQueue = new StackQueue();
        stackQueue.enQueue(1);
        stackQueue.enQueue(2);
        stackQueue.enQueue(3);
        System.out.println(stackQueue.deQueue());
        System.out.println(stackQueue.deQueue());
        stackQueue.enQueue(4);
        System.out.println(stackQueue.deQueue());
        System.out.println(stackQueue.deQueue());
    }
}

 

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