返回栈中最小元素

/**
 * 实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返
      回栈中最小元素的操作。
     【要求】
   1.pop、push、getMin操作的时间复杂度都是O(1)。
   2.设计的栈类型可以使用现成的栈结构。
 * @author Colin
 *
 */
public class StackGetMin {

	private Stack<Integer> data;
	private Stack<Integer> help;
	
	public StackGetMin() {
		this.data = new Stack<Integer>();
		this.help = new Stack<Integer>();
	}
	
	public void push(Integer num){
		data.push(num);
		if(help.isEmpty()){
			help.push(num);
		}else{
			help.push(num>help.peek()?help.peek():num);
		}
	}
	
	public Integer pop(){
		help.pop();
		return data.pop();
	}
	
	public Integer peek(){
		return data.peek();
	}
	
	public Integer getMin(){
		return help.peek();
	}

猜你喜欢

转载自blog.csdn.net/qq_42667028/article/details/86667127