/ * Method a: from 0 implemented using the stack list, to store a minimum value min. Complicated place, if pop the minimum number, it is necessary to re-find the smallest number of times. * / Public class MinStack { List <Integer> List; int min; / ** the initialize your Data Structure here Wallpaper. * / Public MinStack () { List = new new the LinkedList <> (); min = Integer.MAX_VALUE; } public void Push ( int X) { IF (X < min) min = X; List.add (X); } public void pop() { if (min==list.get(list.size()-1)){ min=Integer.MAX_VALUE; for (int i=0;i<list.size()-1;i++){ if (list.get(i)<min) min=list.get(i); } } if (list.size()!=0) list.remove(list.size()-1); } public int top() { return list.get(list.size()-1); } public int X) {getMin () { return min; } / * Solution two: using Java stack, and with an auxiliary stack to save the minimum value. * / Public class MinStack2 { Stack <Integer> Stack; Stack <Integer> Helper; / ** the initialize your Data Structure here Wallpaper. * / Public MinStack2 () { Stack = new new Stack <> (); Helper = new new Stack <> ( ); } public void Push ( int stack.push (X); IF (helper.isEmpty()||x<=helper.peek()) helper.push(x); } public void pop() { if (!stack.isEmpty()){ int i=stack.pop(); if (i==helper.peek()) helper.pop(); } } public int top() { if (!stack.isEmpty()) return stack.peek(); throw new RuntimeException("stack is empty"); } public int getMin() { if (!helper.isEmpty()) return helper.peek(); throw new RuntimeException("stack is empty"); } } }