#include <stdio.h>
#include <stdlib.h>
typedef struct heapstruct {
elementtype *elements;//存放堆元素的数组
int size;//堆得当前元素个数
int capacity;//堆的最大容量
}*maxheap;
maxheap create(int maxsize){//创建容量为maxsize的空的最大堆
maxheap h=(maxheap)malloc(sizeof(struct heapstruct));
h->elements=(elementype)malloc((maxsize+1)*sizeof(elementype));
h->size=0;
h->capacity=maxsize;
h->elements[0]=maxdata;//定义哨兵为最大值方便以后更快操作
return h;
}
//堆的插入
void insert(maxheap h,elementtype item ){
int i;
if(isfull(h)){
printf("最大堆已满");
return 0;
}
i=++h->size;
for(;h->elements[i/2]<item;i/=2){
h->elements[i]=h->elements[i/2];
}
h->elements[i]=item;
}
//堆的删除
elementtype deletemax(maxheap h) {
int parent,child;//从堆中去除最大值并删除
elementtype maxitem ,temp;
if(isempty(h)){
printf("最大堆为空\n");
return 0;
}
maxitem=h->elements[1];//取出根节点最大值
//用最大堆中的最后一个元素从根节点开始向上过滤下层节点
temp=h->elements[h->size--];
for(parents=1;parent*2<=h->size;parent=child){
child=parent*2;
if((child!=h->size)&&(h->elements[child]<h->elements[child+1])){
child++;//child指向左右子节点的较大者
}
if(temp>=h->elements[child])break;
else h->elements[parent]=h->elements[child];
//else目的->移动temp元素到下一层
}
h->elements[parent]=temp;
return maxitem;
}
int main(){
}
最大堆的删除
最新推荐文章于 2023-05-04 08:00:00 发布