常数时间内查找栈中最小的元素

import java.util.Stack;

/**
 * @Author JH
 * @CreateDate 18-6-9
 * @Description 栈中最小的元素
 */
public class MinStack E extends Integer{
    private StackE minStack=new StackE();
    private StackE element=new StackE();
    public E min(){
        if (!minStack.isEmpty())
        return minStack.peek();
        return null;
    }
    public void push(E e){
        element.push(e);
        if (!minStack.isEmpty()){
           E min=minStack.peek();
           if (e.compareTo(min)0){
               minStack.push(e);
           }else{
               minStack.push(min);
           }
         }else{
            minStack.push(e);
        }
    }
    public E pop(){
        if (!element.isEmpty()){
            minStack.pop();
            return element.pop();
        }
        return null;
    }
    public  void print(){
        while (!element.isEmpty()){
            System.out.print(element.pop()+"  ");
        }
    }
    public static void main(String[] args) {
        MinStackInteger s=new MinStackInteger();
        s.push(3);
        System.out.println(s.min());
        s.push(4);
        System.out.println(s.min());
        s.push(2);
        System.out.println(s.min());
        s.push(3);
        System.out.println(s.min());
        s.pop();
        System.out.println(s.min());
        s.pop();
        System.out.println(s.min());
        s.pop();
        s.push(0);
        System.out.println(s.min());
        System.out.println(s.minStack.size());
    }
}
最新回复(0)
/jishuo8nJUIdG77eBnOrEu0iRWufXYdwDs1uwqiiAyw3r0Gg_3D4794803
8 简首页