• 剑指offer 面试题9:用两个栈实现队列


    题目描述

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    使用栈实现队列的下列操作:push(x) -- 将一个元素放入队列的尾部pop() -- 从队列首部移除元素peek() -- 返回队列首部的元素empty() -- 返回队列是否为空。

    你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

    编程思想

    由于队列是先进先出的,而栈是先进后出的,所以要用2个栈来实现队列的入队出队功能。队列的入队,与栈的一样。队列的出队,先将第一个栈中的元素全部弹出,并倒入到第二个栈中,将第二个栈中栈顶元素弹出,并将stack2中剩下的元素倒回到stack1中,即实现一次出队。

    编程实现

    class MyQueue {
    public:
        /** Initialize your data structure here. */
        
        stack<int> s1, s2;
        
        MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        void push(int x) {
            while(!s2.empty()) {
                s1.push(s2.top());
                s2.pop();
            }
            s2.push(x);
            while(!s1.empty()) {
                s2.push(s1.top());
                s1.pop();
            }
        }
        
        /** Removes the element from in front of queue and returns that element. */
        int pop() {
            int a = s2.top();
            s2.pop();
            return a;
        }
        
        /** Get the front element. */
        int peek() {
            return s2.top();
        }
        
        /** Returns whether the queue is empty. */
        bool empty() {
            return s2.empty();
        }
    };

    题目总结

    掌握队列和栈的特性。

  • 相关阅读:
    迭代器和生成器
    函数嵌套
    页面调用dll
    C++MFC之picture control控件铺满图片
    C++中去掉string字符串中的 等
    C++之map使用
    C++之条形码,windows下zint库的编译及应用(二)
    C++之条形码,windows下zint库的编译及应用(一)
    C++通过HTTP请求Get或Post方式请求Json数据(转)
    从长字符串中获取想要的字符串
  • 原文地址:https://www.cnblogs.com/parzulpan/p/11258271.html
Copyright © 2020-2023  润新知