#include <stdlib.h>
#include "heap_tree.h"
#define swap(a,b) do{typeof(a) t=a; a=b; b=t;}while(0)
// 调整堆
static void adjust_heap(Heap* heap,int root)
{
while(root*2 <=heap->cnt)
{
int min = root*2;
if(min+1 <= heap->cnt &&
1==heap->cmp(heap->arr[min-1],heap->arr[min]))
min++;
if(1!=heap->cmp(heap->arr[root-1],heap->arr[min-1]))
return;
swap(heap->arr[root-1],heap->arr[min-1]);
root = min;
}
}
// 创建堆
Heap* create_heap(size_t cal)
{
Heap* heap = malloc(sizeof(Heap));
heap->arr = malloc(sizeof(void*)*cal);
heap->cal = cal;
heap->cnt = 0;
heap->cmp = NULL;
return heap;
}
// 堆空
bool empty_heap(Heap* heap)
{
return 0 == heap->cnt;
}
// 堆满
bool full_heap(Heap* heap)
{
return heap->cnt == heap->cal;
}
// 入堆
bool push_heap(Heap* heap,void* data)
{
if(full_heap(heap))
return false;
heap->arr[heap->cnt++] = data;
for(int i=heap->cnt/2; i>0; i--)
adjust_heap(heap,i);
return true;
}
// 出堆
bool pop_heap(Heap* heap)
{
if(empty_heap(heap))
return false;
heap->arr[0] = heap->arr[--heap->cnt];
adjust_heap(heap,1);
return true;
}
// 堆顶
void* top_heap(Heap* heap)
{
return heap->arr[0];
}
// 销毁
void destroy_heap(Heap* heap)
{
free(heap->arr);
free(heap);
}
// 设置比较函数
void setcmp_heap(Heap* heap,CMP cmp)
{
heap->cmp = cmp;
}
/*
int cmp(const void* p1,const void* p2)
{
if(*(int*)p1 > *(int*)p2)
return 1;
if(*(int*)p1 < *(int*)p2)
return -1;
return 0;
}
int main()
{
Heap* heap = create_heap(15);
setcmp_heap(heap,cmp);
for(int i=0; i<10; i++)
{
int* p = malloc(4);
*p = rand()%90+10;
push_heap(heap,p);
}
while(!empty_heap(heap))
{
printf("%d ",*(int*)top_heap(heap));
pop_heap(heap);
}
}
*/
头文件
#ifndef HEAP_TREE_H
#define HEAP_TREE_H
#include <stdio.h>
#include <stdbool.h>
typedef int (*CMP)(const void*,const void*);
typedef struct Heap
{
void** arr;
size_t cal;
size_t cnt;
CMP cmp;
}Heap;
// 创建堆
Heap* create_heap(size_t cal);
// 堆空
bool empty_heap(Heap* heap);
// 堆满
bool full_heap(Heap* heap);
// 入堆
bool push_heap(Heap* heap,void* data);
// 出堆
bool pop_heap(Heap* heap);
// 堆顶
void* top_heap(Heap* heap);
// 销毁
void destroy_heap(Heap* heap);
// 设置比较函数
void setcmp_heap(Heap* heap,CMP cmp);
#endif//HEAP_TREE_H