JAVA实现包含main函数的栈问题(《剑指offer》)

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
import java.util.Stack;
 
public class Solution {
    Stack<Integer> stack = new Stack<>();
    Stack<Integer> minStack = new Stack<>();
 
    public void push(int node) {
        stack.push(node);
        if (minStack.isEmpty()) {
            minStack.push(node);
        } else {
            minStack.push(Math.min(node, minStack.peek()));
        }
    }
 
    public void pop() {
        if (!stack.isEmpty()) {
            stack.pop();
            minStack.pop();
        }
    }
 
    public int top() {
        return stack.peek();
    }
 
    public int min() {
        if (minStack.isEmpty())
            return Integer.MIN_VALUE;
        return minStack.peek();
    }
}


你可能感兴趣的:(JAVA实现包含main函数的栈问题(《剑指offer》))