设计一个有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());
	}
}


你可能感兴趣的:(面试相关算法--栈和队列)