Learning data structure - an array of queues described

To get started Queue friends ~ (God knows why I'm so happy)
First of all, the old rules, before you begin, given the abstract class queue

template<class T>
class queue
{
public:
    virtual ~queue(){}
    virtual bool empty()const=0;//返回true,当且仅当队列为空
    virtual int size()const=0;//返回队列中元素个数
    virtual T& front()=0;//返回头元素的引用
    virtual T& back()=0;//返回尾元素的引用
    virtual void pop()=0;//删除首元素
    virtual void push(const T& theElement)=0;//把元素theElement加入队尾
};

Array describing the queue can be written loop through the array, focusing on whether the queue is full judgment.
If studded queue, the queue is empty and the queue full condition as determined, in order to avoid this situation, the queue can not be studded with this method, a maximum number of queue elements are arrayLength-1. In determining whether it is necessary to use a queue to be full time:
IF ((+ theback. 1) == theFront arraylength%)
arraylength queue length of the array is
theback is the position of the tail of the array, theFront array before the position of the head of a
specific look FIG lower
Here Insert Picture Description
understand this, look queue array described:

class arrayQueue:public queue<T>
{
private:
    int theFront;//队首
    int theBack;//队尾
    int arrayLength;//数组长度
    T *queue;
public:
    arrayQueue(int initialCapacity=10)//构造函数
    {
        theBack=0;
        theFront=0;
        arrayLength=initialCapacity;
        queue=new T[arrayLength];
    }
    bool empty()const
    {
        if(theBack==theFront)
            return true;
        return false;
    }
    int size()const
    {
        return (theBack-theFront+arrayLength)%arrayLength;
    }
    T& front()
    {
        if(theBack==theFront)
            //抛出异常,队列为空
        int tmp=(theFront+1)%arrayLength;
        return queue[tmp];
    }
    T& back()
    {
        if(theBack==theFront)
            //抛出异常,队列为空
        return queue[theBack];
    }
    void pop()
    {
        if(theBack==theFront)
            //抛出异常,队列为空
        theFront=(theFront+1)%arrayLength;//更新theFront的值
        queue[theFront].~T();  //在数组上调用一个Template模板的析构函数
    }
    void push(const T& theElement);
};
void arrayQueue<T>::push(const T& theElement)
{
    if((theBack + 1) % arrayLength == theFront)//如果队列将要满
        //增加数组长度
    theBack=(theBack+1)%arrayLength;
    queue[theBack]=theElement;
}
Published 32 original articles · won praise 12 · views 1365

Guess you like

Origin blog.csdn.net/qq_18873031/article/details/103399752