155--MinStack

/*
    解法一:使用链表从0实现栈,用min来存放最小值。
            复杂的地方是,如果pop了最小的数,就要遍重新找到最小的数。
 */
public class MinStack {
    List<Integer> list;
    int min;
    /** initialize your data structure here. */
    public MinStack() {
        list=new LinkedList<>();
        min=Integer.MAX_VALUE;
    }

    public void push(int x) {
        if (x<min)
            min=x;
        list.add(x);
    }

    public void pop() {
        if (min==list.get(list.size()-1)){
            min=Integer.MAX_VALUE;
            for (int i=0;i<list.size()-1;i++){
                if (list.get(i)<min)
                    min=list.get(i);
            }
        }
        if (list.size()!=0)
            list.remove(list.size()-1);

    }

    public int top() {
        return list.get(list.size()-1);
    }

    public int getMin() {
        return min;
    }
    /*
        解法二:使用Java的栈,并用一个辅助栈来存最小值。
     */
    public class MinStack2{
        Stack<Integer> stack;
        Stack<Integer> helper;
        /** initialize your data structure here. */
        public MinStack2() {
            stack=new Stack<>();
            helper=new Stack<>();
        }

        public void push(int x) {
            stack.push(x);
            if (helper.isEmpty()||x<=helper.peek())
                helper.push(x);
        }

        public void pop() {
            if (!stack.isEmpty()){
                int i=stack.pop();
                if (i==helper.peek())
                    helper.pop();
            }
        }

        public int top() {
            if (!stack.isEmpty())
                return stack.peek();
            throw new RuntimeException("stack is empty");
        }

        public int getMin() {
            if (!helper.isEmpty())
                return helper.peek();
            throw new RuntimeException("stack is empty");
        }
    }

}

 

posted @ 2019-09-19 13:09  张玉昊  阅读(132)  评论(0编辑  收藏  举报