zoukankan      html  css  js  c++  java
  • 用2个stack模拟一个queue

    #include <iostream>
    #include <stack>
    using namespace std;
    
    class MyQueue{
    public:
        void push(int value);
        void pop();
        int front();
        int back();
        bool empty();
    private:
        stack<int> stackPush;
        stack<int> stackPop;
    };
    
    void MyQueue::push(int value)
    {
        stackPush.push(value);
    }
    
    void MyQueue::pop()
    {
        if (stackPop.empty())
            while(!stackPush.empty()){
                stackPop.push(stackPush.top());
                stackPush.pop();
            }
    
        if (!stackPop.empty())
            stackPop.pop();
        else 
            cout<<"Queue already empty!"<<endl;
    }
    
    int MyQueue::front()
    {
        if (stackPop.empty())
            while(!stackPush.empty()){
                stackPop.push(stackPush.top());
                stackPush.pop();
            }
    
        if (!stackPop.empty())
            return stackPop.top();
        else {
            cout<<"Queue already emtpy!"<<endl;
            return -1;
        }
    }
    
    int MyQueue::back()
    {
        if (!stackPush.empty())
            return stackPush.top();
        
        else if (stackPush.empty() && !stackPop.empty()){
            stack<int> stackTmp;
            while (!stackPop.empty()){
                stackTmp.push(stackPop.top());
                stackPop.pop();
            }
            int returnValue = stackTmp.top();
            while (!stackTmp.empty()){
                stackPop.push(stackTmp.top());
                stackTmp.pop();
            }
            return returnValue;
        }
    
        else if (stackPush.empty() && stackPop.empty()){
            cout<<"queue already empty!"<<endl;
            return -1;
        }
    }
    
    bool MyQueue::empty()
    {
        if (stackPush.empty() && stackPop.empty())
            return true;
        return false;
    }
    
    int main()
    {
        MyQueue myQueue;
        for (int i = 0; i < 10; i++)
        {
            int value = rand()%100;
            cout<<"EnQueuing element : "<<value<<endl;
            myQueue.push(value);
            cout<<"Current Front Element : "<<myQueue.front()<<"      Current Back Element : "<<myQueue.back()<<endl<<endl;
        }
        cout<<"Push over!"<<endl;
        while (!myQueue.empty())
        {
            cout<<"DeQueuing element : "<<myQueue.front()<<endl;
            myQueue.pop();
        }
    
        return 0;
    }

    EOF

  • 相关阅读:
    Loadrunner中web_find和web_reg_find函数的使用与区别
    性能测试之LoardRunner 检查点
    性能测试之LoardRunner 自动关联
    性能测试之LoardRunner 手动关联二
    性能测试之LoardRunner 手动关联一
    性能测试之LoadRunner11 破解
    JavaScript break跳出多重循环
    如何将jsp页面的table报表转换到excel报表导出
    Word撤销键(Ctrl+z)无效的解决方法
    sql执行顺序
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2809887.html
Copyright © 2011-2022 走看看