找出栈中最小的元素

时间:2021-08-21 09:51:38
package stack;


/**
 * 找出栈中最小的元素
 * 先定义一个辅助栈,栈顶永远存最小的元素。如原栈中添加元素比辅助栈顶元素大,辅助栈的栈顶元素复制一遍
 * 放到辅助栈中,如果小,则直接放到辅助栈中。
 */
import java.util.Stack;


public class MinStack {
private Stack<Integer> stack=new Stack<Integer>();
private Stack<Integer> minStack=new Stack<Integer>();
public void push(int data){
stack.push(data);
if(minStack.size()==0 || minStack.peek()>data)
minStack.add(data);
else{
int date=minStack.peek();
minStack.add(date);//核心代码,peek返回的是栈顶代码
System.out.println("peek="+date+":minsize="+minStack.size());
}
}

public int pop() throws Exception{
if(stack.size()==0)
throw new Exception("栈中空了");
int data=stack.pop();
System.out.println("data="+data);
int mindata=minStack.pop();//核心代码,原栈出,辅助栈也出。
System.out.println("mindata="+mindata);
return data;
}
public Object min() throws Exception{
if(minStack.size()==0)
throw new Exception("栈中空了");
return minStack.peek();
}
public static void main(String[] args) throws Exception {
MinStack  minstack=new MinStack();
minstack.push(5);
minstack.push(7);
minstack.push(3);
minstack.push(4);
System.out.println(minstack.pop());
System.out.println(minstack.pop());
System.out.println("min="+minstack.min());

}
}