第一题 实现一个栈

127 阅读1分钟

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。 示例:

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

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/ba… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 要实现一个栈,自定义一个链表吧,同时需要快速获得最小值;给最小值也定义一个链表; 每一次增加都会判断最大和最小的链表

private Node<Integer> stack;

private Node<Integer> max;

private Node<Integer> min;

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

public void push(int x) {
   stack = new Node<>(x,stack);
   if(max == null || max.elem <= x){
       max = new Node<>(x,max);
   }
   if (min == null || min.elem >= x){
       min = new Node<>(x,min);
   }
}

public void pop() {
    if(Objects.isNull(stack)){
        return;
    }
    if (stack.elem.equals(max.elem)){
        max = max.next;
    }
    if (stack.elem.equals(min.elem)){
        min = min.next;
    }
    stack = stack.next;
}

public int top() {
    return max.elem;
}

public int min() {
    return min.elem;
}

public static class Node<E>{
    E elem;
    Node<E> next;

    public Node(E elem, Node<E> next) {
        this.elem = elem;
        this.next = next;
    }

    public Node() {
    }
}