队列中取最大值操作问题

来源:互联网 发布:棋牌源码哪个好 编辑:程序博客网 时间:2024/05/22 09:46

1、利用栈中O(1)的时间复杂度取最大值的思路,使用两个栈构建一个队列;
2、然后取出两个栈中的较大者即为队列的最大值。

#include <stack>#include <exception>#include <iostream>using namespace  std;class SatckMax{public:    void push(int x)    {        dataStack.push(x);        if (maxStack.empty())        {            maxStack.push(x);        }        else        {            maxStack.push( x > maxStack.top() ? x :maxStack.top());        }    }    void pop()    {        if (dataStack.empty())        {            throw new exception("Empty Satck");            return ;        }         dataStack.pop();        maxStack.pop();    }    int top()    {        if (maxStack.empty())        {            throw new exception("Empty Satck");            return 0;        }         else        {            return dataStack.top();        }    }    int Max()    {        if (maxStack.empty())        {            throw new exception("Empty Satck");            return 0;        }         else        {            return maxStack.top();        }    }    bool empty()    {        return dataStack.empty();    }protected:private:    stack<int> dataStack;    stack<int> maxStack;};class QueueMax{public:    void push(int x)    {        SA.push(x);    }    void pop()    {        if (SB.empty())        {            while(!SA.empty())            {                SB.push(SA.top());                SA.pop();            }        }        if (SB.empty())        {            throw new exception("Empty Queue");            return;        }        SB.pop();    }    int Max()    {        if (SA.empty())        {            return SB.Max();        }        if (SB.empty())        {            return SA.Max();        }        return (SA.Max()>SA.Max()? SA.Max():SB.Max());    }protected:private:    SatckMax SA;    SatckMax SB;};void test(){    QueueMax SM;    SM.push(2);    cout<<SM.Max()<<endl;    SM.push(1);    cout<<SM.Max()<<endl;    SM.push(3);    cout<<SM.Max()<<endl;    SM.push(0);    cout<<SM.Max()<<endl;    SM.pop();    cout<<SM.Max()<<endl;    SM.pop();    cout<<SM.Max()<<endl;    SM.pop();    cout<<SM.Max()<<endl;    //SM.Max();}

结果
2
2
3
3
3
3
0

0 0