20.栈中最小元素的min函数

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))

import java.util.Stack;

/*
 * 解题注意:原栈多大,min栈就多大
 * 23521
 * 22221
 * 题目意思是当前最小,你data栈pop掉1以后,当前min就改变了
 */
public class Solution20 {
    Stack<Integer> stackData = new Stack<Integer>();
    Stack<Integer> stackMin = new Stack<Integer>();

    public void push(int node) {
        if (stackMin.size() == 0) {
            stackData.push(node);
            stackMin.push(node);
        } else {
            if (node < stackMin.peek()) {
                stackMin.push(node);
                stackData.push(node);
            } else {
                stackData.push(node);
                stackMin.push(stackMin.peek());
            }
        }
    }

    public void pop() {
        stackData.pop();
        stackMin.pop();
    }

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

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

}
原文地址:https://www.cnblogs.com/yuange678/p/10816263.html