return the minimum value in a stack

Implement a stack which not only has push, pop, but also is able to return the minimum value within O(1) time.

public class StackWithMin {
	Stack<Integer> stack1 = new Stack<Integer>();
	Stack<Integer> stack2 = new Stack<Integer>();
	
	public void push(int value) {
		if (value <= min()) {
			stack2.push(value);
		}
		stack1.push(value);
	}
	public int pop() {
		if (stack1.peek() == stack2.peek() ) {
			stack2.pop();
		}
		return stack1.pop();
	}
	public int min() {
		if (stack2.peek() == null) {
			return MAX_INT;
		} else {
			return stack2.peek();
		}
	}
}
转载请注明出处: http://blog.csdn.net/beiyeqingteng

你可能感兴趣的:(null,Class)