数据结构
struct PriorityQueue{
int MAXNUM;
int n;
DataType *pq;
};
typedef struct PriorityQueue *PPriorityQueue;
struct PriorityQueue{ int MAXNUM; //容量 int n; //个数 DataType *pq; //数据};向优先队列中插入一个元素
void add_heap(PPriorityQueue papq, DataType x){
int i;
if(papq->n>=papq->MAXNUM)
{
printf("FULL!\n");return ; //判断是否溢出
}
for(i = papq->n;i>0 && papq->pq[(i-1)/2]>x; i=(i-1)/2) // 从第一空节点的父节点开始判断其是否大于x,模拟出来就是将大于x的节点均向下移动,相对而言就是空节点向根移动
papq->pq[i] = papq->pq[(i-1)/2]; //将值往下挪动,变相认为腾出空间
papq->pa[i] = x;
papq->n++;//插入,n要加1
}
删除优先队列最小元
void removeMin_heap(PPriorityQueue papq)
{
int s,i,child;
DataType temp;
if(isEmpty_heap(papq)) {printf("Empty!\n"); return ;}
s = --papq->n; //先删除
temp = papq->pq[s]; //把最后的元素赋给temp
i = 0; child = 1; //
while(child<s){ //找寻最后元素存放的位置
if(child<s-1 && papq->pq[child] > papq->pq[child+1]) //选择比较小的子节点
child++;
if(temp > papq->pq[child]) //空位向叶节点移动
{
papq->pq[i] = papq->pq[child];
i=child;
child = 2*i+1;
}
else break; //已经找到了适当的位置
}
papq->pq[i] = temp; //把最后位置填入
}
判断优先队列是否为空
int isEmpty_heap(PPriorityQueue papq)
{
return(papq->n==0);
}