首页 > 其他 > 详细

leetcode_num155_Min Stack

时间:2015-03-30 18:52:31      阅读:219      评论:0      收藏:0      [点我收藏+]

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 {
    public:
        void push(int x) {
            stack1.push(x);
            if(stack2.empty())
                stack2.push(x);
            else{
                int tmp=stack2.top();
                if(x>tmp)
                    stack2.push(tmp);
                else
                    stack2.push(x);
            }
        }
    
        void pop() {
            if((!stack1.empty())&&(!stack2.empty())){
                stack1.pop();
                stack2.pop();
            }
            else
                cout<<"EMPTY!"<<endl;
            
        }
    
        int top() {
            if(!stack1.empty())
                return stack1.top();
        }
    
        int getMin() {
            if(!stack2.empty())
                return stack2.top();
            
        }
    private:
        stack<int> stack1;
        stack<int> stack2;
    };

leetcode_num155_Min Stack

原文:http://blog.csdn.net/eliza1130/article/details/44752701

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!