劍指之包含min函數的棧

定義棧的數據結構,請在該類型中實現一個能夠得到棧中所含最小元素的min函數(時間複雜度應爲O(1))

import java.util.Stack;
public class Solution {
   private Stack<Integer> stack = new Stack<Integer>(); 
   private Stack<Integer> minStack=new Stack<Integer>();
    //每次放一個數的時候都要判斷最小棧中的數
    public void push(int node) {
        stack.push(node);
        if (minStack.isEmpty()) {
            minStack.push(node);
        } else {
            if (node <= minStack.peek()) {
                minStack.push(node);
            }
        }
    }
    
    public void pop() {
        if (stack.isEmpty()) {
            return;
        } else {
            if (stack.pop() == minStack.peek()) {
                minStack.pop();
            }
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return minStack.peek();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章