数据结构——树——通用堆

#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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值