数据结构复盘——最大堆

#include 
#include 

typedef struct HNode *Heap;

//定义
struct HNode{
     
	int *data;
	int size;
	int capacity;
};
typedef Heap MaxHeap;

//初始化
MaxHeap CreateHNode(int MAXSIZE){
     
	MaxHeap H=(MaxHeap)malloc(sizeof(struct HNode));
	H->data=(int *)malloc((MAXSIZE+1)*sizeof(int));
	H->size=0;
	H->capacity=MAXSIZE;
	H->data[0]=1000;
	return H;
}

//判满
bool IsFull(MaxHeap H){
     
	return (H->size==H->capacity);
}

//插入
bool Insert(MaxHeap H,int x){
     
	int i;

	if(IsFull(H)){
     
		printf("满!");
		return false;
	}
	i=++H->size;
	for(;H->data[i/2]<x;i/=2){
     
		H->data[i]=H->data[i/2];
		H->data[i]=x;
	}
	return true;
}

//判空
bool IsEmpty(MaxHeap H){
     
	return (H->size==0);
}

//删除
int Delete(MaxHeap H){
     
	int parent,child;
	int Max,x;

	if(IsEmpty(H)){
     
		printf("空!");
		return -1;
	}
	Max=H->data[1];
	x=H->data[H->size--];
	for(parent=1;parent*2<=H->size;parent=child){
     
		child=parent*2;
		if((child!=H->size) && (H->data[child]<H->data[child+1])){
     
			child++;
		}
		if(x>=H->data[child])break;
		else
			H->data[parent]=H->data[child];
	}
	H->data[parent]=x;
	return Max;
}

//主方法
void main(){
     
	MaxHeap H=CreateHNode(10);
	int n,x;

	printf("请输入数据个数:");
	scanf("%d",&n);
	for(int i=0;i<n;i++){
     
		scanf("%d",&x);
		Insert(H,x);
	}

	while(!IsEmpty(H)){
     
		printf("%d ",Delete(H));
	}
}

你可能感兴趣的:(数据结构)