堆的代码实现如下:
1.Heap.c
#include "Heap.h"
//初始化
void HPInit(HP* php)
{
assert(php);
php->arr = NULL;
php->capacity = php->size = 0;
}
void swap(int* x, int* y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}
//向上调整
void Adjustup(HPDataType* arr, int child)
{
int parent = (child - 1) / 2;
while (child > 0)
{
if (arr[child] < arr[parent])
{
swap(&arr[parent], &arr[child]);
child = parent;
parent = (child - 1) / 2;
}
else
{
break;
}
}
}
//入堆
void HPPush(HP* php, HPDataType x)
{
assert(php);
//判断空间是否足够
if (php->size == php->capacity)
{
int newCapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
//扩容
HPDataType* tmp = (HPDataType*)realloc(php->arr, newCapacity * sizeof(HPDataType));
if (tmp == NULL)
{
perror("realloc fail!");
exit(1);
}
php->arr = tmp;
php->capacity = newCapacity;
}
php->arr[php->size] = x;
Adjustup(php->arr, php->size);
++php->arr;
}
//出堆
void HPPop(HP* php)
{
assert(php && php->size);
swap(&php->arr[0], &php->arr[php->size - 1]);
--php->size;
Adjustdown(php->arr, 0, php->size);
}
//向下调整
void Adjustdown(HPDataType* arr, int parent, int n)
{
int child = parent * 2 + 1;//左孩子
while (child < n)
{
if (child + 1 < n && arr[child] > arr[child + 1])
{
child++;
}
if (arr[child] < arr[parent])
{
swap(&arr[child], &arr[parent]);
parent = child;
child = parent * 2 + 1;
}
else
{
break;
}
}
}
//取出堆顶的元素
HPDataType HPTop(HP* php)
{
assert(php);
return php->arr[php->arr[0]];
}
//判空
bool HPEmpty(HP* php)
{
assert(php);
return php->size == 0;
}
//销毁
void HPDestory(HP* php)
{
if (php->arr)
{
free(php->arr);
}
php->arr = NULL;
php->size = php->capacity = 0;
}
2.Heap.h文件
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
typedef int HPDataType;
typedef struct Heap
{
HPDataType* arr;
int size;//有效的数据个数
int capacity;//空间大小
}HP;
//初始化
void HPInit(HP* php);
//入堆
void HPPush(HP* php, HPDataType x);
//向上调整
void Adjustup(HPDataType* arr, int child);
//出堆
void HPPop(HP* php);
//向下调整
void Adjustdown(HPDataType* arr, int parent, int n);
//取出堆顶的元素
HPDataType HPTop(HP* php);
//判空
bool HPEmpty(HP* php);
//销毁
void HPDestory(HP* php);