美文网首页
剑指offer-栈

剑指offer-栈

作者: Catherin_gao | 来源:发表于2021-01-15 11:59 被阅读0次

    一. 堆栈的总结

    二. Easy 题目

    2,1 剑指 Offer 09. 用两个栈实现队列

    class CQueue {
    private:
        stack<int> stack1,stack2;
    public:
        CQueue() {
            while(!stack1.empty()){
               stack1.pop();
            }
            while(!stack2.empty()){
               stack2.pop();
            }
        }
        
        void appendTail(int value) {
            stack1.push(value);
        }
        
        int deleteHead() {
            int value =-1;
            if(!stack2.empty()){
                value=stack2.top();
                stack2.pop();
            }else{
                while(!stack1.empty()){
                    stack2.push(stack1.top());
                    stack1.pop();
                }
                if(!stack2.empty()){
                value=stack2.top();
                stack2.pop();}
            }
            return value;
        }
    };
    

    2.2 剑指 Offer 30. 包含min函数的栈

    • 最小栈和最大队列的思路不一样。
    class MinStack {
    private:
      stack<int> stack1;
      stack<int> min_s;
    public:
        /** initialize your data structure here. */
        MinStack() {
        }
        
        void push(int x) {
           stack1.push(x);
           if(min_s.empty()||x<= min_s.top() ){
               min_s.push(x);
           }
        }
        
        void pop() {
           if(min_s.top() == stack1.top()){
               min_s.pop();
           }
          stack1.pop();
        }
        
        int top() {
           return stack1.top();
        }
        
        int min() {
           return min_s.top();
        }
    };
    
    

    相关文章

      网友评论

          本文标题:剑指offer-栈

          本文链接:https://www.haomeiwen.com/subject/rnjvgktx.html