Set up an auxiliary stack. Whenever an element is placed in the stack, the current minimum value is also placed in the auxiliary stack;
whenever the stack is popped, the current value and the current minimum value are simultaneously popped out of the stack. The code is as follows :
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() || node < minStack.peek()){
minStack.push(node);
}else{
minStack.push(minStack.peek());
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int min() {
return minStack.peek();
}
}
Reference:
https://blog.csdn.net/jsqfengbao/article/details/47260355
https://blog.csdn.net/u012289407/article/details/46564841