st0le
4/28/2013 - 7:34 PM

Stack with Min()

Stack with Min()


    class StackMin extends Stack {
		private Stack minStack;

		public StackMin(int size) {
			super(size);
			minStack = new Stack(size);
		}
		
		@Override
		public void push(int item) throws Exception {
			if(empty() || item <= minStack.peek())
				minStack.push(item);
			super.push(item);
		}
		
		@Override
		public int pop() throws Exception {
			int item = super.pop();
			if(item == minStack.peek())
				minStack.pop();
			return item;
		}
		
		public int min() throws Exception {
			if(empty()) throw new Exception("Stack is empty.");
			return minStack.peek();
		}

	}