/*
题目:
	定义一个含max函数的队列类,并实现pop_front()、push_back()、max()函数。
*/
#include<iostream>
#include<cstdlib>
#include<stack>
#include<string>
#include<vector>
#include<deque>

using namespace std;

template<typename T>class QueueWithMax{
public:
    void pop_front(){
        if(myQueue.empty()) throw("queue is empty");
        if(myQueue.front().index == queueMax.front().index){
            queueMax.pop_front();
        }
        myQueue.pop_front();
    }

    void push_back(T number){
        while(!queueMax.empty() && myQueue.back().number <= number){
            queueMax.pop_back();
        }
        InternalData interalData = {number,index};
        myQueue.push_back(interalData);
        queueMax.push_back(interalData);
        index++;
    }

    T max() const{
        if(queueMax.empty()) throw ("queue is empty");

        return queueMax.back().number;
    }

private:
    struct InternalData{
        T number;
        int index;
    };

    deque<InternalData> myQueue;
    deque<InternalData> queueMax;
    int index;
};



int main()
{
    QueueWithMax<int> queue;
    queue.push_back(5);
    queue.push_back(3);
    queue.pop_front();
    cout<<queue.max();

}

   

posted on 2019-12-29 15:17  笨宝宝  阅读(164)  评论(0编辑  收藏  举报