1.什么是堆?
2.堆的抽象数据类型描述
3.堆的C语言实现
#include<stdio.h>
#include<stdlib.h>#define ElementType int
#define MaxData 100
typedef struct HeapStruct *MaxHeap;
struct HeapStruct{ElementType *Elements;int Size;int Capacity;
};//1.初始化
MaxHeap Create(int MaxSize)
{MaxHeap H;H=(MaxHeap)malloc(sizeof(struct HeapStruct));H->Elements=malloc((MaxSize+1)*sizeof(ElementType));H->Size=0;H->Capacity=MaxSize;H->Elements[0]=MaxData;return H;
}//2.判断堆是否满
int IsFull(MaxHeap H)
{return H->Size==H->Capacity;
}//3.插入
void Insert(ElementType item,MaxHeap H)
{int i;if(IsFull(H)){printf("堆已满\n");return;}i=++H->Size;for(;H->Elements[i/2]<item;i/=2){H->Elements[i]=H->Elements[i/2];}H->Elements[i]=item;
}//4.判断堆是否为空
int IsEmpty(MaxHeap H)
{return H->Size==0;
}//5.删除最大值
ElementType DeleteMax(MaxHeap H)
{int Parent,Child;ElementType MaxItem,temp;if(IsEmpty(H)){printf("堆为空,无法删除\n");return;}MaxItem=H->Elements[1];temp=H->Elements[H->Size--];for(Parent=1;Parent*2<=H->Size;Parent=Child){Child=Parent*2;if(Child!=H->Size&&(H->Elements[Child]<H->Elements[Child+1])){Child++;}if(temp>=H->Elements[Child]){break;}else{H->Elements[Parent]=H->Elements[Child];}}H->Elements[Parent]=temp;return MaxItem;
}int main()
{int i;MaxHeap H;H=Create(10);Insert(32,H);Insert(18,H);Insert(21,H);Insert(12,H);Insert(15,H);for(i=0;i<=H->Size;i++){printf("%d ",H->Elements[i]);}printf("\n");Insert(45,H);for(i=0;i<=H->Size;i++){printf("%d ",H->Elements[i]);}printf("\n");int DMax;DMax=DeleteMax(H);for(i=0;i<=H->Size;i++){printf("%d ",H->Elements[i]);}printf("\n");return 0;
}