leetcode-min stack

来源:互联网 发布:中国税务网络大学登录 编辑:程序博客网 时间:2024/06/06 15:03

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.
class MinStack {    private LinkedList<Integer> stack=new LinkedList<Integer>();    int min=Integer.MAX_VALUE;   // if it's min the initial value should be max    public void push(int x) {        stack.add(x);        if(x<min)min=x;    }    public void pop() {      Integer cur=stack.removeLast();      if(cur==min){          min=Integer.MAX_VALUE;  // this should be max          for(Integer a:stack){              if(a<min)min=a;          }      }    }    public int top() {        return stack.get(stack.size()-1);    }    public int getMin() {       return min;     }}


0 0