问题描述
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
实现栈的push(), pop()及getMin()函数,要求函数的时间复杂度为O(1).
解决思路
使用两个栈,一个为普通栈,实现push和pop函数;另一个记录所有入栈元素的非递增序列;
如下图所示:

程序
public class MinStack {
private Stack<Integer> normal;
private Stack<Integer> min;
public MinStack() {
normal = new Stack<Integer>();
min = new Stack<Integer>();
}
public void push(int elem) {
normal.push(elem);
if (min.isEmpty() || min.peek() >= elem) {
min.push(elem);
}
}
public int pop() throws Exception {
if (normal.isEmpty()) {
throw new Exception("Error: The Stack is Empty!");
}
int res = normal.pop();
if (min.peek() == res) {
min.pop();
}
return res;
}
public int getMin() throws Exception {
if (min.isEmpty()) {
throw new Exception("Error: The Stack is Empty!");
}
return min.peek();
}
}
原文:http://www.cnblogs.com/harrygogo/p/4605949.html