劍指offer4J【C2 P9】兩個棧實現(xiàn)隊列,兩個隊列實現(xiàn)棧

題目

兩個棧實現(xiàn)隊列

題解

比較簡單 就不多解釋了 看代碼吧

class Queue {
    private Deque<Integer> stackIn = new LinkedList<>();
    private Deque<Integer> stackOut = new LinkedList<>();
    private int defaultValue = -1;

    public void offer(int value) {
        stackIn.push(value);
    }

    public int poll() {
        if (stackOut.isEmpty()) {
            if (stackIn.isEmpty()) {
                return defaultValue;
            } else {
                while (!stackIn.isEmpty()) {
                    stackOut.push(stackIn.pop());
                }
            }
        }
        return stackOut.pop();
    }
}

題目

兩個隊列實現(xiàn)棧

題解

也不難 不浪費(fèi)時間了

class Stack {
    private Deque<Integer>[] queues = new Deque[]{new LinkedList<Integer>(), new LinkedList<Integer>()};
    private int status = 0;
    private int defaultValue = -1;

    public void push(int value) {
        queues[status % 2].offer(value);
    }

    public int pop() {
        while (true) {
            int index = status % 2;
            int next = (status + 1) % 2;
            if (queues[index].size() < 1) return defaultValue;
            while (queues[index].size() > 1)
                queues[next].offer(queues[index].poll());
            status=(status+1)%2;
            return queues[index].poll();
        }
    }
}

總結(jié): 這類題目考驗對數(shù)據(jù)結(jié)構(gòu)的理解,與靈活性,不要死記硬背,練死勁,講究四兩撥千斤,接化發(fā),更不能搞偷襲,耍小聰明來湊夠字?jǐn)?shù) 哈

源碼: 劍指offer4J

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容