• 225.用队列实现栈


    原题链接

    题解

    可以直接使用一个queue直接解决,在进行push()操作的时候,当我们每插入一个元素,都要保证我们新插入的元素要在队头,这就要每一次插入的时候进行队列的反转,因为从开始插入的时候就反转,所以我们新插入的元素的前面的元素都是符合要求的(即后面插入的数据比前面插入的数据在队列的前面),所以直接将前面的数据添加到现插入的数据的后面实现反转。

    代码如下

    class MyStack {
    public:
        queue<int> q;
        /** Initialize your data structure here. */
        MyStack() {
    
        }
        
        /** Push element x onto stack. */
        void push(int x) {
            int n = q.size();//记录未插入前的数量,每一次插入前面的已经是反转的队列顺序
            q.push(x);
            while(n --){
                int t = q.front();
                q.pop();
                q.push(t);
            }
        }
        
        /** Removes the element on top of the stack and returns that element. */
        int pop() {
            int t = q.front();
            q.pop();
            return t;
        }
        
        /** Get the top element. */
        int top() {
            return q.front();
        }
        
        /** Returns whether the stack is empty. */
        bool empty() {
            return q.empty();
        }
    };
    
    /**
     * Your MyStack object will be instantiated and called as such:
     * MyStack* obj = new MyStack();
     * obj->push(x);
     * int param_2 = obj->pop();
     * int param_3 = obj->top();
     * bool param_4 = obj->empty();
     */
    

    每一次都保证先插入的数据在后插入的数据之后,最后就是队列变成栈了

  • 相关阅读:
    WinForm的Chart控件画条形图
    WinForm的Chart控件画折线图
    自定义控件
    左侧收缩菜单
    数组
    C#生成随机数的三种方法
    WinForm之GDI手动双缓冲技术
    WinForm之GDI画图步骤
    WinForm GDI编程:Graphics画布类
    翻译:《实用的Python编程》08_02_Logging
  • 原文地址:https://www.cnblogs.com/Lngstart/p/13338096.html
Copyright © 2020-2023  润新知