数据结构与算法:队列 arrayQueue

#ifndef arrayQueue_
#define arrayQueue_

#include "queue.h"
#include "myExceptions.h"
#include <sstream>

using namespace std;

template<class T>
class arrayQueue : public queue<T>
{
   public:
      arrayQueue(int initialCapacity = 10);
      ~arrayQueue() {delete [] queue;}
      bool empty() const {return theFront == theBack;}
      int size() const
          {return (theBack - theFront + arrayLength) % arrayLength;}
      T& front()
         {// 返回头元素的引用
            if (theFront == theBack)
               throw queueEmpty();
            return queue[(theFront + 1) % arrayLength];
         }
      T& back()
         {// 返回尾元素的引用
            if (theFront == theBack)
               throw queueEmpty();
            return queue[theBack];
         }
      void pop()
           {// 删除首元素
              if (theFront == theBack)
                 throw queueEmpty();
              theFront = (theFront + 1) % arrayLength;
              queue[theFront].~T();  // T 的析构函数
           }
      void push(const T& theElement);  // 把元素 theElement 加入队尾
   private:
      int theFront;       // 逆时针方向,指向列首元素的下一个位置
      int theBack;        // 尾元素的位置
      int arrayLength;    // 队列容量
      T *queue;           // 元素数组
};

template<class T>
arrayQueue<T>::arrayQueue(int initialCapacity)
{// Constructor.
   if (initialCapacity < 1)
   {ostringstream s;
    s << "Initial capacity = " << initialCapacity << " Must be > 0";
    throw illegalParameterValue(s.str());
   }
   arrayLength = initialCapacity;
   queue = new T[arrayLength];
   theFront = 0;
   theBack = 0;
}

template<typename T>
void arrayQueue<T>::push(const T& theElement)
{// 把元素 theElement 加入队列
   
    if ((theBack + 1) % theFront == theFront)
    {// 加倍数组长度
        // 分配新的数组空间
        T* newQueue = new T[theFront * 2];

        // 把原数组复制到新数组
        int start = (theFront + 1) % arrayLength;
        if (start < 2)
            // 没有形成环
            copy(queue + start, queue + arrayLength, newQueue);
        else
        {// 队列形成环
            copy(queue + start, queue + theFront, newQueue);
            copy(queue, queue + theBack + 1, newQueue + arrayLength - start);
        }
        theFront = 2 * arrayLength - 1;
        theBack = arrayLength - 2;          // 队列长度 - 1
        arrayLength *= 2;
        delete [] queue;
        queue = newQueue;
   }

   // 把元素 theElement 插入队列的尾部
    theBack = (theBack + 1) % arrayLength;
    queue[theBack] = theElement;
}

#endif

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值