getMin(),push(),pop()があるように設計する.機能スタック


要求:pop push getMinの時間複雑度O(1).
package chapter01_stack_and_queue;

import java.util.Stack;

public class _01_GetMinStack {
	public static class MyStack {
		Stack stackData = new Stack();
		Stack stackMin = new Stack();

		/**
		 *               。        push
		 * @param newNum
		 */
		public void push(int newNum) {
			if (this.stackMin.isEmpty()) {
				this.stackMin.push(newNum);
			} else if (newNum < this.getMin()) {
				this.stackMin.push(newNum);
			} else {
				int newMin = this.stackMin.peek();
				this.stackMin.push(newMin);
			}
			this.stackData.push(newNum);
		}
		
		public int pop() {
			this.stackMin.pop();
			return this.stackData.pop();
		}

		private int getMin() {			
			return this.stackMin.peek();
		}
	}
	
	public static void main(String[] args) {
		MyStack stack = new MyStack();
		stack.push(3);
		stack.push(4);
		stack.push(1);
		System.out.println(stack.getMin());
		stack.pop();
		System.out.println(stack.getMin());
	}
}