import java.io.InputStream;
import java.util.Stack;
public class minStack {
private Stack<Integer> mainStack=new Stack<Integer>();
private Stack<Integer> minStack=new Stack<Integer>();
/**
* 入栈操作
* @param element
*/
public void push(int element){
mainStack.push(element);
if(minStack.isEmpty()||element<=minStack.peek()){
minStack.push(element);
}
}
/**
* 出栈操作
* @return
*/
public int pop(){
if(mainStack.peek().equals(minStack.peek())){
minStack.pop();
}
return mainStack.pop();
}
/**
* 得到最小值操作
* @return
* @throws Exception
*/
public int getMin() throws Exception{
if(minStack.isEmpty()){
throw new Exception("stack is empty");
}
return minStack.peek();
}
public static void main(String[] args)throws Exception {
minStack stack=new minStack();
stack.push(4);
stack.push(9);
stack.push(10);
stack.push(1);
stack.push(6);
System.out.println(stack.getMin());
System.out.println(stack.pop());
stack.pop();
System.out.println(stack.getMin());
}
}
最小栈的实现
最新推荐文章于 2020-08-20 22:27:33 发布