用C语言模块实现队列数据结构

来源:互联网 发布:网站排名优化培训 编辑:程序博客网 时间:2024/06/02 16:03
队列这种数据结构与栈一样,是一个工具性的数据结构,通常被其它复杂数据结构所使用。比如实现二叉树的遍历的非递归算法(层次遍历)。下面就用C++模板实现队列数据结构的一个较完整代码!队列可以以用数组,也可以用链表实现,这里只用双向链表实现这一数据结构。

  

//Queue.h  //双链表队列数据结构C++模块的实现  //理论知识参考《数据结构(C语言版)--严慰明》  #ifndef _QUEUE_H_  #define _QUEUE_H_  namespace _QUEUE_  {  //队列中的数据元素  template  class QueueNode  {  public:  QueueNode()  {  this->mElement = 0;  this->mpNext = this->mpPrev = NULL;  }  T mElement;  QueueNode* mpNext;  QueueNode* mpPrev;  };  template  class Queue  {  public:  Queue()  {  QueueNode * pNode = new QueueNode;  pNode->mElement = T(-1);  pNode->mpNext = pNode->mpPrev = NULL;  this->mpHead = this->mpTail = pNode;  }  ~Queue()  {  this->clear();  delete this->mpHead;  this->mpHead = this->mpTail = NULL;  }  bool insert(T element);  T front();  T back();  bool isEmpty(void);  bool clear(void);  int size();  friend ostream& operator《 <>(ostream& ostr,const Queue& q);  private:  QueueNode* mpHead;  QueueNode* mpTail;  };  template  bool Queue::insert(T element)  {  QueueNode * pNode = new QueueNode;  if (pNode == NULL) return false;  pNode->mElement = element;  this->mpTail->mpNext = pNode;  pNode->mpPrev = this->mpTail;  this->mpTail = this->mpTail->mpNext;  return true;  }  template  T Queue::front()  {  T element = T();  QueueNode* pNode = NULL;  if (!this->isEmpty())  {  pNode = this->mpHead->mpNext;  element = pNode->mElement;  this->mpHead ->mpNext = pNode->mpNext;  if (pNode->mpNext)  pNode->mpNext->mpPrev = this->mpHead;  if (pNode == this->mpTail)  this->mpTail = this->mpHead;  delete pNode;  }  return element;  }  template  T Queue::back()  {  T element = T();  QueueNode* pNode = NULL;  if (!this->isEmpty())  {  pNode = this->mpTail;  element = pNode->mElement;  this->mpTail = this->mpTail->mpPrev;  this->mpTail->mpNext = NULL;  delete pNode;  }  return element;  }  template  bool Queue::isEmpty(void)  {  return (this->mpTail == this->mpHead);  }  template  bool Queue::clear(void)  {  while (!this->isEmpty())  this->back();  return true;  }  template  int Queue::size()  {  int iCount = 0;  if (!this->isEmpty())  {  QueueNode* pNode = this->mpTail;  while (pNode != this->mpHead)  {  iCount++;  pNode = pNode->mpPrev;  }  }  return iCount;  }  template  ostream& operator《 <>(ostream& ostr,const Queue& q)  {  QueueNode* pNode = q.mpHead->mpNext;  while (pNode != NULL)  {  ostr 《 pNode->mElement 《 ",";  pNode = pNode->mpNext;  }  return ostr;  }  }  #endif

  以上就是队列数据结构的实现。

原创粉丝点击