zoukankan      html  css  js  c++  java
  • Implement Queue using Stacks

    class Queue {
    public:
       stack<int>sta1;
       stack<int>sta2;
        // Push element x to the back of queue.
        /*
        入栈:把元素push到sta1中;
        出栈:sta2作为辅助栈,如果sta2不为空,则把sta2中的元素挨个出站,然后把sta1的元素压入sta2中,把栈顶元素出栈.最后要把sta2中的元素压入sta1中
        */
        void push(int x) {
            sta1.push(x);
           
           
        }

        // Removes the element from in front of queue.
        void pop(void) {
           
            while( !sta1.empty())
            { sta2.push(sta1.top());
             sta1.pop();
            }
            sta2.pop();
            while( !sta2.empty())//pop()之后要把sta2中的元素压入sta1中
            {
            sta1.push(sta2.top());
            sta2.pop();
            }
        }

        // Get the front element.
        int peek(void) {
            int a = 0;

            while(!sta1.empty())
            {sta2.push(sta1.top());
             sta1.pop();
            }
            a=sta2.top();
            while( !sta2.empty())//pop()之后要把sta2中的元素压入sta1中
            {
            sta1.push(sta2.top());
            sta2.pop();
            }
            return a;
        }

        // Return whether the queue is empty.
        bool empty(void) {
           
          return ( sta1.empty() && sta2.empty());
           
        }
    };

  • 相关阅读:
    学习Javascript闭包(Closure)
    JS的this原理
    页面锚点的设置
    JS异常捕获和抛出
    C++ 指针初始化要注意的地方
    Jupyter Notebook里面使用Matplotlib画图 图表中文乱码问题
    Matplotlib 基本图表的绘制
    Matplotlib 子图的创建
    Matplotlib 图表的样式参数
    Matplotlib 图表的基本参数设置
  • 原文地址:https://www.cnblogs.com/gofighting/p/5036199.html
Copyright © 2011-2022 走看看