实现了两个普通的队列,一个优先权队列

本文介绍了C++中三种队列的实现方式:基于数组的固定大小队列、链式队列及优先级队列。通过具体代码展示了每种队列的特点和使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       C++ 基础内容, 不值一提

AuthorJacky Wu       2006-5-5

引用该文章,必须注明其出处              http://blog.youkuaiyun.com/imwkj

 

 两个普通的队列,还有一个是利用链表队列实现的优先级队列,没什么好说的,使用了简单的继承,看代码就明白了

#ifndef QUEUE_H_

#define QUEUE_H_

 

#include "Chain.h"

 

#include <cassert>

#include <cstddef>

#include <stdexcept>

 

//固定事务数的队列

//用数组实现

template <class Type>

class FixQueue {

public:

   FixQueue( size_t sz );

   virtual ~FixQueue();

  

   bool EnQueue( const Type& item);

   Type DeQueue();

   Type GetFront();

   void MakeEmpty() { m_ifront = m_irear = 0; }

   bool IsEmpty() const { return  m_ifront == m_irear; }

   bool IsFull() const { return (m_irear+1)%m_uiMaxSize == m_ifront; }

   size_t Length() const { return (m_irear+m_uiMaxSize-m_ifront)%m_uiMaxSize; }

private:

   int m_irear, m_ifront;

   Type* m_pElement;

   size_t m_uiMaxSize;

};

 

//--------------------------------------

//FixQueue template implementation

//

template <class Type>

FixQueue<Type>::FixQueue( size_t sz = 15) : m_uiMaxSize(sz)

{

   m_pElement = new Type[m_uiMaxSize];

   assert( m_pElement != 0);   //其实这样做没有作用

   m_ifront = m_irear = 0; 

}

 

template <class Type>

FixQueue<Type>::~FixQueue()

{

   delete []m_pElement;

}

 

template <class Type>

bool FixQueue<Type>::EnQueue( const Type& item )

{

   //队列不满则加入元素

   if(IsFull()) return false;

   m_irear = (m_irear+1) % m_uiMaxSize; //计算队尾值

   m_pElement[m_irear] = item;

   return true;

}

 

template <class Type>

Type FixQueue<Type>::DeQueue()

{

   if(IsEmpty())

   {

      MakeEmpty();

      throw std::out_of_range("Out Of bounds of Queue!/n");

   }

   else

   {

      m_ifront = (m_ifront+1) % m_uiMaxSize;

      return m_pElement[m_ifront];  

   }

}

 

template <class Type>

Type FixQueue<Type>::GetFront()

{

   //返回队列头元素的值

   if(IsEmpty())

   {

      MakeEmpty();

      throw std::out_of_range("Out Of bounds of Queue!/n");

   }

   else

   {

      return m_pElement[(m_ifront+1) % m_uiMaxSize];

   } 

}

 

//FixQueue Over!

 

//ChainQueue

//链式队列,虽然链式队列从抽象意义上来说"is a Chain"

//但是仔细分析,很容易发现链式队列只不过是能够在"链头删除元素""链尾添加元素"的普通链表

//更好的表示是: 链式队列"has a general Chain for specific use"

template <class Type>

class ChainQueue {

public:

   ChainQueue();

   virtual ~ChainQueue();

  

   virtual void EnQueue( const Type& item);

   virtual Type DeQueue();

   Type GetFront();

   void MakeEmpty();

   bool IsEmpty() const;

   size_t Length() const ;

 

private:

   Chain<Type> chain;

};

 

 

template <class Type>

ChainQueue<Type>::ChainQueue() {}

 

template <class Type>

ChainQueue<Type>::~ChainQueue() {}

template <class Type>

void ChainQueue<Type>::EnQueue( const Type& item)

{

   //新加元素

   try

   {

      chain.Appen(item);

   }

   catch (...)

   { throw; }

}

 

template <class Type>

Type ChainQueue<Type>::DeQueue()

{

   Type tmp;

   try

   {

      chain.Delete(1,tmp);

   }

   catch(...)

   {

      throw;

   }

   return tmp;

}

 

template <class Type>

Type ChainQueue<Type>::GetFront()

{

   Type tmp;

   if(!chain.Find(1,tmp)) throw std::out_of_range("Out Of bounds of Queue!/n");

   return tmp;

}

 

template <class Type>

void ChainQueue<Type>::MakeEmpty()

{

   chain.Erase();

}

 

template <class Type>

bool ChainQueue<Type>::IsEmpty() const

{

   return (chain.Length() == 0);

}

 

template <class Type>

size_t ChainQueue<Type>::Length() const

{

   return (size_t)chain.Length();

}

 

 

//============================================================

//PRQueue 实现一个按优先权重操作的队列

//显然,无需重新实现完整的优先权队列

//优先权队列只不过是一个特殊的队列罢了,优先级队列插入元素方式不同,

//overwrite EnQueue();

//这里采用继承链式队列(考虑到元素插入的效率因素,链表划算)

//一个更好的方法是利用交叉链表实现优先级队列,优先级别为行列表,同优先级的任务放到列链表中,这里只是重新实现按权重插入元素

//=============================================================

//定义一个带优先权的结构

template <class Type>

typedef struct PRItem

{

   int priority;   //优先权

   Type item;      //

  

   //只需要重载一个 <=就行了,这样刚好能够实现

   //1:先按照优先级处理

   //2:同优先级的FIFO方式处理

   bool operator<=( const PRItem& item) {

      return priority <= item.priority;

   }

};

 

 

template <class Type>

class PRQueue : public ChainQueue< PRItem<Type> > //郁闷,模板中模板类型

{

  

public:

   PRQueue();

   ~PRQueue();

   void EnQueue( const PRItem<Type>& item)        //overwrite

   {

      typedef PRItem<Type> PRITEM;

 

      typename Chain<PRITEM>::iterator iter = Chain<PRITEM>::chain.begin();

      int x=1;

      //按优先权插入寻找插入位置

      while(iter != Chain<PRITEM>::chain.end() && iter.current() <= item)

      {

         x++;

         iter++;

      }

     

      Chain<PRITEM>::chain.Insert(x, item);

   }

  

   void EnQueue( const Type& item, int priority)     //overload

   {

      PRItem<Type> tmp;

      tmp.item = item;

      tmp.priority = priority;

      EnQueue(tmp);     

   }

  

};

 

 

#endif /*QUEUE_H_*/

 

### C语言实现优先队列的数据结构 由于C语言的标准库未直接提供优先队列的支持,可以借助其他数据结构来构建这一功能。一种常见的方法是利用最大堆或最小堆作为底层存储机制[^2]。 #### 使用数组模拟的最大堆实现优先队列 下面展示了一个简单的基于最大堆的优先队列实现方式: ```c #include <stdio.h> #include <stdlib.h> #define MAX_HEAP_SIZE 100 typedef struct { int data[MAX_HEAP_SIZE]; int size; } PriorityQueue; void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } // 插入新元素到优先队列中 void push(PriorityQueue* pq, int value) { if (pq->size >= MAX_HEAP_SIZE - 1) return; // 防止溢出 int i = ++pq->size; while ((i != 1) && (value > pq->data[i / 2])) { // 维护大根堆性质 pq->data[i] = pq->data[i / 2]; i /= 2; } pq->data[i] = value; } // 移除并返回最高优先级的元素 int pop(PriorityQueue* pq) { if (pq->size == 0) exit(-1); // 如果为空则退出程序 int rootValue = pq->data[1]; // 记录当前最大的值 int lastElement = pq->data[pq->size--]; // 获取最后一个节点用于调整位置 int parentIndex = 1; int childIndex; do { childIndex = parentIndex * 2; // 找较大的子结点 if ((childIndex < pq->size) && (pq->data[childIndex] < pq->data[childIndex + 1])) childIndex++; if (lastElement >= pq->data[childIndex]) break; pq->data[parentIndex] = pq->data[childIndex]; parentIndex = childIndex; } while(childIndex <= pq->size); pq->data[parentIndex] = lastElement; return rootValue; } ``` 此代码片段定义了一种名为`PriorityQueue`的新类型,并实现两个基本操作:向队列中添加元素(`push`)以及移除具有最高优先权的元素(`pop`)。这里采用的是最大堆的形式,因此每次取出的都是数值上最大的那个元素;如果希望得到相反的结果,则只需修改比较条件即可转变为最小堆形式。 为了使上述函数正常工作,在调用之前还需要初始化一个`PriorityQueue`实例并将它的大小设置为零。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值