1. 程式人生 > 其它 >劍指offer09 用兩個棧實現佇列

劍指offer09 用兩個棧實現佇列

題目

用兩個棧實現一個佇列。佇列的宣告如下,請實現它的兩個函式 appendTail 和 deleteHead ,分別完成在佇列尾部插入整數和在佇列頭部刪除整數的功能。(若佇列中沒有元素,deleteHead操作返回 -1 )

示例 1:
輸入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
輸出:[null,null,3,-1]

示例 2:
輸入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
輸出:[null,-1,null,null,5,2]

提示:
1 <= values <= 10000
最多會對appendTail、deleteHead 進行10000次呼叫

方法

  • 時間複雜度:O(1),插入為O(1),刪除雖然有時是O(n),但均攤下來是O(1)
  • 空間複雜度:O(n)
class CQueue {
    private Stack<Integer> pushStack ;
    private Stack<Integer> popStack;

    public CQueue() {
        this.pushStack = new Stack();
        this.popStack = new Stack();

    }
    
    public void appendTail(int value) {
        pushStack.push(value);
    }
    
    public int deleteHead() {
        if(popStack.isEmpty()){
            while(!pushStack.isEmpty()){
                popStack.push(pushStack.pop());
            }
        }
        if(popStack.isEmpty()){
            return -1;
        }
        return popStack.pop();
    }
}