編寫一個(gè)類,用兩個(gè)棧實(shí)現(xiàn)隊(duì)列,支持隊(duì)列的基本操作(add、poll、peek)

本題來自程序員代碼面試指南


編寫一個(gè)類,用兩個(gè)棧實(shí)現(xiàn)隊(duì)列,支持隊(duì)列的基本操作(add、poll、peek)

實(shí)現(xiàn)思路

一個(gè)棧作為壓入棧,在壓入數(shù)據(jù)時(shí)只往這個(gè)棧中壓入,記為stackPush;
另一個(gè)棧只作為彈出棧,在彈出數(shù)據(jù)時(shí)只從這個(gè)棧彈出,記為stackPop。
實(shí)現(xiàn)這個(gè)有倆個(gè)關(guān)鍵點(diǎn)

  • 1.如果stackPush要往stackPop中壓入數(shù)據(jù),那么必須一次性把stackPush中的數(shù)據(jù)全部壓入。
  • 2.如果stackPop不為空,stackPush絕對(duì)不能向stackPop中壓入數(shù)據(jù)。
    java Stack類中的isEmpty()和empty()的區(qū)別
public class TwoStacksQueue {
    private Stack<Integer> stackPush;//壓入數(shù)據(jù)棧
    private Stack<Integer> stackPop; //彈出數(shù)據(jù)棧

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

    /**
     * 入隊(duì)操作
     * 直接將數(shù)據(jù)壓入壓入數(shù)據(jù)棧
     * @param push
     */
    public void push(int push) {
        this.stackPush.push(push);
    }


    /**
     * 出隊(duì)操作
     * @return
     */
    public int poll() throws Exception {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new Exception("隊(duì)列中沒有數(shù)據(jù)");
        } else if (stackPop.isEmpty()) {
            //彈出數(shù)據(jù)棧為空,可以將整個(gè)壓入數(shù)據(jù)棧中的數(shù)據(jù)倒入彈出數(shù)據(jù)棧
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    /**
     * 返回隊(duì)頭元素
     * @return
     * @throws Exception
     */
    public int peek() throws Exception {
        if (stackPush.isEmpty() && stackPop.isEmpty()) {
            throw new Exception("隊(duì)列中沒有數(shù)據(jù)");
        }else if (stackPop.isEmpty()) {
            //彈出數(shù)據(jù)棧為空,可以將整個(gè)壓入數(shù)據(jù)棧中的數(shù)據(jù)倒入彈出數(shù)據(jù)棧
            while (!stackPush.isEmpty()) {
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }
}

附上github地址

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

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

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