题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
import java.util.Stack; public class Solution { private Stack<Integer> data = new Stack<>(); private Stack<Integer> min = new Stack<>(); Integer temp = null; public void push(int node) { if(temp != null) { if(temp > node) { temp = node; min.push(node); } data.push(node); }else { temp = node; min.push(node); data.push(node); } } public void pop() { int node = data.pop(); if(node == temp) { min.pop(); temp = min.peek(); } } public int top() { return data.peek(); } public int min() { return min.peek(); } }