包含min函数的栈

题目:
设计一个栈,它可以在O(1)的时间内实现push,pop和min操作,所谓min操作就是得到栈中最小的元素。

经典问题。

package suanfa;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class Stack {
	
	private int[]obj=new int[1000];
	private int top=-1;
	private Map<Integer,Integer> minMap=new HashMap();
	public void push(int  value) throws Exception{
		
		  if(top==1000){
			  throw new Exception("can not push any data !");
		  }
		  if(top<0){
			  minMap.put(++top, value);
			  obj[top]=value;
		  }
		  else{
			  
			  if(minMap.get(top)>value){
				minMap.put(++top, value);
				obj[top]=value;
			  }
			  else{
				  int tempvalue=minMap.get(top);
				  minMap.put(++top,tempvalue );
				  obj[top]=value;
			  }
		  } 	
	}
	public int pop() throws Exception{
		
		if(top>=0){
			minMap.remove(top);
			return obj[top--];
		}
		else
			throw new Exception("no data");
		
	}
	public int min() throws Exception{
		if(top>=0)
		return minMap.get(top);
		else
			throw new Exception("no data");
		
	}
	public static void main(String[] args)  {
		Stack stack=new Stack();
		Random random=new Random();
		for (int i=0;i<5;i++){
			try {
				stack.push(random.nextInt(10));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		for(int k=0;k<5;k++){
			try {
				int j=stack.min();
				int r=stack.pop();
				System.out.println("the min is "+j+"  and the pop is "+r);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

 

你可能感兴趣的:(min函数的栈)