包含min函數的棧_20

題目描述

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

注意:保證測試中不會當棧爲空的時候,對棧調用pop()或者min()或者top()方法。

 

 

//peek() 查看此堆棧頂部的對象。
public class Stack_20 {
    Stack<Integer> stackTotal = new Stack<Integer>();
    Stack<Integer> stackLittle = new Stack<Integer>();
    public void push(int node) {
        stackTotal.push(node);
        if (stackLittle.isEmpty()) {
            stackLittle.push(node);
        }else {
            if (node <= stackLittle.peek()) {
                stackLittle.push(node);
            }else {
                stackLittle.push(stackLittle.peek());
            }
        }
    }

    public void pop() {
        stackTotal.pop();
        stackLittle.pop();
    }

    public int top() {
        return stackTotal.peek();
    }

    public int min() {
        return stackLittle.peek();
    }

    public static void main(String[] args) {
        Stack_20 stack_20 = new Stack_20();
        int[] array = {3,4,2,1};
        for (int i=0; i<array.length; i++) {
            stack_20.push(array[i]);
        }
        int min = stack_20.min();
        System.out.println(min);
        stack_20.pop();
        int min1 = stack_20.min();
        System.out.println(min1);
        int top = stack_20.top();
        System.out.println(top);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章