这里用数组(顺序表)实现一个二叉树
Heap.h
c
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int HPDataType;
typedef struct Heap
{
HPDataType* a;
int size;
int capacity;
}HP;
void HPInit(HP* php);
void HPDestory(HP* php);
void Swap(HPDataType* p1, HPDataType* p2);
void AdjustUp(HP* php, int child);
void AdjustDown(HP* php);
void HPPush(HP* php, HPDataType x);
void HPPop(HP* php);
HPDataType HPTop(HP* php);
int HPSize(HP* php);
bool ISEmpty(HP* php);
Heap.c
c
#include"Heap.h"
void HPInit(HP* php)
{
assert(php);
php->a = NULL;
php->size = php->capacity = 0;
}
void HPDestory(HP* php)
{
assert(php);
free(php->a);
php->a = NULL;
php->size = php->capacity = 0;
}
//交换函数:
void Swap(HPDataType* p1, HPDataType* p2)
{
HPDataType tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
//向上调整元素:(小堆)
void AdjustUp(HP* php,int child)
{
assert(php);
assert(php->size);
int parent = (child - 1) / 2;
while (child != parent)
{
if (php->a[child] < php->a[parent])
{
Swap(&php->a[child], &php->a[parent]);
parent = child;
parent = (child - 1) / 2;
}
else
break;
}
}
//向下调整:(小堆)
void AdjustDown(HP* php)
{
assert(php);
int parent = 0;
int child = 2 * parent + 1;
while (child<php->size)
{
if (child+1<php->size&&php->a[child] > php->a[child + 1])
child = child + 1;
if (php->a[parent] > php->a[child])
{
Swap(&php->a[parent], &php->a[child]);
parent = child;
child = 2 * child + 1;
}
else
break;
}
}
//插入元素:
void HPPush(HP* php, HPDataType x)
{
int newcapacity = (php->capacity == 0) ? 4 : php->capacity * 2;
if (php->capacity == php->size)
{
HPDataType* tmp = (HPDataType*)realloc(php->a, sizeof(HPDataType) * newcapacity);
php->a = tmp;
}
php->a[php->size] = x;
php->size++;
AdjustUp(php, php->size - 1);
}
//删除堆顶元素:
void HPPop(HP* php)
{
assert(php);
assert(php->size);
Swap(&php->a[php->size - 1], &php->a[0]);
php->size--;
AdjustDown(php);
}
//取出栈顶元素:
HPDataType HPTop(HP* php)
{
assert(php);
assert(php->size);
return php->a[0];
}
//计算元素个数:
int HPSize(HP* php)
{
assert(php);
assert(php->size);
return php->size;
}
//判断堆是否为空:
bool ISEmpty(HP* php)
{
assert(php);
return php->size == 0;
}
test.c
c
#include"Heap.h"
int main()
{
int arr[10] = { 5,9,1,3,7,6 };
HP hp;
HPInit(&hp);
int sz = sizeof(arr) / sizeof(int);
for (int i = 0;i <6;i++)
{
HPPush(&hp, arr[i]);
}
while (!ISEmpty(&hp))
{
int k = HPTop(&hp);
printf("%d ", k);
HPPop(&hp);
}
printf("\n");
return 0;
}