Min Stack

来源:互联网 发布:大数据数据库选择 编辑:程序博客网 时间:2024/05/23 20:41

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 =new Stack<Integer>();
        private Stack<Integer>minstack=new Stack<Integer>();
        public void push(int x) {
            if(minstack.isEmpty()||x<=minstack.peek())
            minstack.push(x);
            stack.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(); 
        }
    }
  • 参考博文:http://blog.csdn.net/ljiabin/article/details/40982153
0 0
原创粉丝点击