最小栈
最小栈
java">class MinStack {private Stack<Integer> stack;private Stack<Integer> minstack;public MinStack() {stack=new Stack<>();minstack=new Stack<>();}public void push(int val) {stack.push(val);if(minstack.empty()){minstack.push(val);}else{ //=要加上,否则stack中此数有多个 出栈时minstack也要出栈 数不够只有一个if(val<=minstack.peek()){minstack.push(val);}}}public void pop() {if(!stack.empty()){int ret=stack.pop();if(minstack.peek()==ret){minstack.pop();}}}//获取正常栈顶元素public int top() {if(stack.empty()){return -1; //oj题中轻易不要抛出异常 直接return-1即可}return stack.peek();}//获取最小栈顶元素public int getMin() {if(minstack.empty()){return -1;}return minstack.peek();}
}