• 用栈实现队列


      具体思路:

    通过两个栈来模拟

    class MyQueue {
    public:
        /** Initialize your data structure here. */
        stack<int>q1;
        stack<int>q2;
        MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        void push(int x) {
           while(!q2.empty()){
               q1.push(q2.top());
               q2.pop();
           }
           q1.push(x);
            while(!q1.empty()){
                q2.push(q1.top());
                q1.pop();
            }
            return ;
        }
        
        /** Removes the element from in front of queue and returns that element. */
        int pop() {
            int tmp = 0;
            if(!q2.empty()){
                tmp = q2.top();
                q2.pop();
            }
            return tmp;
        }
        
        /** Get the front element. */
        int peek() {
            int tmp = 0;
            if(!q2.empty()){
                tmp = q2.top();
            }
            return tmp;
        }
        
        /** Returns whether the queue is empty. */
        bool empty() {
            return q2.empty();
        }
    };
    
    /**
     * Your MyQueue object will be instantiated and called as such:
     * MyQueue* obj = new MyQueue();
     * obj->push(x);
     * int param_2 = obj->pop();
     * int param_3 = obj->peek();
     * bool param_4 = obj->empty();
     */
  • 相关阅读:
    linux 邮件服务器
    Nginx学习之keepalive
    explain 和 desc 详解
    mysql 常用语句
    loop设备及losetup命令
    cryptsetup文件系统加密
    ftp主动与被动模式详解
    大型网站关键技术
    大访问量网站架构设计
    Mysql 的事务隔离级别
  • 原文地址:https://www.cnblogs.com/letlifestop/p/11564493.html
Copyright © 2020-2023  润新知