定義棧的資料結構,請在該型別中實現一個能夠得到棧中所含最小元素的min函式(時間複雜度應為O(1))。
阿新 • • 發佈:2018-12-02
import java.util.Stack; public class Solution { private Stack<Integer> min_stack=new Stack<Integer>(); private Stack<Integer> data_stack=new Stack<Integer>(); public void push(int node) { if(min_stack.isEmpty()||min_stack.peek()>=node) { min_stack.push(node); } else{ min_stack.push(min_stack.peek()); } data_stack.push(node); } public void pop() { if(data_stack.empty()||min_stack.empty()) return; data_stack.pop(); min_stack.pop(); } public int top() { if(!data_stack.empty()) { return data_stack.peek(); } return 0; } public int min() { if(!min_stack.empty()) { return min_stack.peek(); } return 0; } }