具有返回最小值功能的栈

  • Post author:
  • Post category:其他


import java.util.Stack;
class newStack{
	private Stack<Integer> s;          // 普通的栈
	private Stack<Integer> sMin;    //负责弹出最小值的栈
	
	public newStack() {
		this.s = new Stack<Integer>();
		this.sMin = new Stack<Integer>();
	}
	
	public void push(int value) {
		s.push(value);
		if (this.sMin.isEmpty()) {
			this.sMin.push(value);
		} else {
			if (value < this.sMin.peek()) {
				this.sMin.push(value);
			}
		}
	}
	
	public int pop() {
		if (this.s.isEmpty()) {
			throw new RuntimeException("Stack is empty");
		}
		int value = this.s.pop();
		if (value == this.getMin()) {
			this.sMin.pop();
		}
		return value;
	}
	
	public int getMin() {
		if (this.sMin.isEmpty()) {
			throw new RuntimeException("Stack is empty");
		}
		return this.sMin.peek();
	}	
}



版权声明:本文为qq_41409907原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。