刷题-Min Stack 缺python

来源:互联网 发布:淘宝小号挂机赚钱 编辑:程序博客网 时间:2024/04/29 03:22

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.

  • getMin() -- Retrieve the minimum element in the stack.
java:
class MinStack {
    Node top = null ;
    public void push(int x) {
        if (top == null){
            top = new Node(x);
            top.min = x;
        }
        else{
            Node temp = new Node(x);
            temp.next = top;
            top = temp;
            top.min = Math.min(top.next.min,x);
            
        }
    }


    public void pop() {
        top = top.next;
        return;
    }


    public int top() {
        return top == null ? 0 : top.val; 
    }


    public int getMin() {
        return top == null ? 0:top.min;
    }
}


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

0 0
原创粉丝点击