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

  • 相关阅读:
    LeetCode 183. Customers Who Never Order (从不订购的客户)
    LeetCode 182. Duplicate Emails (查找重复的电子邮箱)
    LeetCode 181. Employees Earning More Than Their Managers (超过经理收入的员工)
    LeetCode 176. Second Highest Salary (第二高的薪水)
    CMake Tutorial
    osx c++连接mysql
    为mysql 表重新设置自增的主键id
    更改pandas dataframe 列的顺序
    会场安排问题
    nlpir分词器过期处理
  • 原文地址:https://www.cnblogs.com/lihaozy/p/2809887.html
Copyright © 2011-2022 走看看