Min stack

来源:互联网 发布:photoshopcs4软件下载 编辑:程序博客网 时间:2024/06/07 23:30

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 Stack<Integer> stack;    private Stack<Integer> minStack;    public MinStack() {        stack = new Stack<Integer>();        minStack = new Stack<Integer>();    }    public void push(int x) {        stack.push(x);        if (minStack.empty() == true)            minStack.push(x);        else        if (Integer.parseInt(minStack.peek().toString()) >= x)            minStack.push(x);    }    public void pop() {        if (stack.peek().equals(minStack.peek()) )              minStack.pop();         stack.pop();    }    public int top() {        return stack.peek();    }    public int getMin() {        return minStack.peek();    }}

0 0
原创粉丝点击