1.3 棧(3)


套路

  • 暫無(wú)

注意點(diǎn)

  • Stack : empty() ,ArrayDeque / LinkedList:isEmpty()
  • poll()、top()、peek()、min()操作都需要排除棧為空的情況 !stack.empty()

目錄

  • 包含min函數(shù)的棧
  • 棧的壓入、彈出序列(實(shí)際過(guò)程模擬還需要練習(xí))
  • 用兩個(gè)棧實(shí)現(xiàn)隊(duì)列

包含min函數(shù)的棧

定義棧的數(shù)據(jù)結(jié)構(gòu),請(qǐng)?jiān)谠擃?lèi)型中實(shí)現(xiàn)一個(gè)能夠得到棧最小元素的min函數(shù)。

Stack<Integer> stack = new Stack<>();
Stack<Integer> stackMin = new Stack<>();

public void push(int node) {
    stack.push(node);
    if (stackMin.empty()) {
        stackMin.push(node);
    } else if (node <= stackMin.peek()) {
        stackMin.push(node);
    }
}

public void pop() {
    if (stack.empty()) {
        throw new EmptyStackException("this stack is empty !");
    } else {
        if (stack.pop() == stackMin.peek()) {
            stackMin.pop();
        }
    }
}

public int top() {
    if (stack.empty()) {
        throw new EmptyStackException("this stack is empty !");
    } else {
        return stack.peek();
    }
}

public int min() {
    if (stackMin.empty()) {
        throw new EmptyStackException("this stack is empty !");
    } else {
        return stackMin.peek();
    }
}

棧的壓入、彈出序列

輸入兩個(gè)整數(shù)序列,第一個(gè)序列表示棧的壓入順序,請(qǐng)判斷第二個(gè)序列是否為該棧的彈出順序。假設(shè)壓入棧的所有數(shù)字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對(duì)應(yīng)的一個(gè)彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個(gè)序列的長(zhǎng)度是相等的)

public boolean IsPopOrder(int [] pushA,int [] popA) {
    if (pushA == null || popA == null || pushA.length != popA.length) {
        return false;
    }
    Stack<Integer> stack = new Stack<>();
    int popIndex = 0;
    for (int i = 0; i < pushA.length; i++) {
        stack.push(pushA[i]);
        while (!stack.empty() && stack.peek() == popA[popIndex]) {
            stack.pop();
            popIndex++;
        }
    }
    return stack.empty();
}

用兩個(gè)棧實(shí)現(xiàn)隊(duì)列

用兩個(gè)棧來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列,完成隊(duì)列的Push和Pop操作。 隊(duì)列中的元素為int類(lèi)型。

  • 解題思路:在將棧1中的元素放入棧2時(shí),只要保證棧2此時(shí)為空,就可以保證正確性。
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
    stack1.push(node);
}

public int pop() {
    if (stack1.empty() && stack2.empty()) {
        return -1;
    }
    if (stack2.empty()) {
        while (!stack1.empty()) {
            stack2.push(stack1.pop());
        }
    }
    return stack2.pop();
}

最后編輯于
?著作權(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),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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