面试题 03.02. 栈的最小值

15 阅读1分钟

面试题 03.02. 栈的最小值

相关企业

提示

请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。

示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

解题答案

class MinStack {

    /** initialize your data structure here. */
    /**
     * initialize your data structure here.
     */
    private Node head;

    public MinStack() {
        this.head = new Node(0, Integer.MAX_VALUE, null);
    }

    public void push(int x) {
        this.head = new Node(x, Math.min(this.head.min, x), head);
    }

    public void pop() {
        this.head = this.head.next;
    }

    public int top() {
        return this.head.val;
    }

    public int getMin() {
        return this.head.min;
    }

    static class Node {
        int val;
        int min;
        Node next;

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