码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_num155_Min Stack

时间:2015-03-30 18:55:43      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   data structure   

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

标签:c++   leetcode   data structure   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!