[leetCode]剑指 Offer 30. 包含min函数的栈

解法

这题的关键是设计一种数据结构,当栈中压入节点时可以同时记录当前栈的最小值

class MinStack {

    class Node{
        int val;
        int min;
        Node next;
        public Node(int val, int min){
            this.val = val;
            this.min = min;
        }
    }

    private LinkedList<Node> stack;

    /** initialize your data structure here. */
    public MinStack() {
        stack = new LinkedList<>();
    }
    
    public void push(int x) {
        if(stack.isEmpty()){
            Node node = new Node(x,x);
            stack.push(node);
        }else{
            Node top = stack.peek();
            int min = Math.min(x,top.min);
            stack.push(new Node(x,min));
        }
    }
    
    public void pop() {
        stack.pop();
    }
    
    public int top() {
        return stack.peek().val;
    }
    
    public int min() {
        return stack.peek().min;
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.min();
 */

自己实现栈

class MinStack {

    class Node{
        int val;
        int min;
        Node next;
        public Node(int val, int min){
            this.val = val;
            this.min = min;
        }
    }

    private Node first;

    /** initialize your data structure here. */
    public MinStack() {

    }
    
    public void push(int x) {
        Node oldfirst = first;
        int min = x;
        if(oldfirst != null){
            min = Math.min(oldfirst.min,x);
        }
        first = new Node(x,min);
        first.next = oldfirst;
    }
    
    public void pop() {
        first = first.next;
    }
    
    public int top() {
       return first.val;
    }
    
    public int min() {
        return first.min;
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.min();
 */

leetCode 主站同题

posted @ 2020-08-24 07:43  消灭猕猴桃  阅读(53)  评论(0编辑  收藏  举报