借助两个栈来实现
public class GetMinStack { private Stack<Integer> stackData; private Stack<Integer> stackMin; public GetMinStack() { this.stackData = new Stack<Integer>(); this.stackMin = new Stack<Integer>(); } public void push(int obj) { if (stackMin.isEmpty()) { stackMin.push(obj); } else { stackMin.push(obj < getmin() ? obj : getmin()); } stackData.push(obj); } public int getmin() { if (stackMin.isEmpty()) { throw new RuntimeException("Your stack is empty."); } return stackMin.peek(); } public int pop() { if (this.stackData.isEmpty()) { throw new RuntimeException("Your stack is empty."); } this.stackMin.pop(); return this.stackData.pop(); } }