
数据结构堆的实现
发布日期:2021-05-08 03:41:15
浏览次数:20
分类:精选文章
本文共 1693 字,大约阅读时间需要 5 分钟。
//假设小堆typedef int HDataType;typedef struct heap{ HDataType* _data; int _size; int _capacity;}heap;void Swap(int* a, int* b){ int tmp = a; a = b; b = tmp;}void heapInit(heap* hp){ if (hp == NULL) return; //空堆 hp->_data = NULL; hp->_size = hp->_capacity = 0; }void heapPush(heap* hp, HDataType val){ checkCapacity(hp); //尾插 hp->_data[hp->_size++] = val; //向上调整 shiftUp(hp->_data, hp->_size, hp->_size - 1);}void hpeaPop(heap* hp){ if (hp->_size > 0) { //交换 Swap(&hp->_data[0], &hp->_data[hp->_size - 1]); hp->_size--; //从堆顶位置向下调整 shiftDown(hp->_data, hp->_size, 0); }}HDataType heapTop(heap* hp){ return hp->_data[0];}int heapEmpty(heap* hp){ if (hp == NULL || hp->_size == 0) return 1; else return 0;}void checkCapacity(heap* hp){ if (hp->_size = hp->_capacity) { int newC = hp->_capacity == 0 ? 1 : 2 * hp->_capacity; hp->_data = (HDataType*)relloc(hp->_data, sizeof(HDataType)*newC); hp->_capacity = newC; }}/*//向下调整#includevoid shiftDown(int* arr, int n, int cur){ //找到孩子的位置 //左孩子 int child = 2 * cur + 1; while (child < n) { //从左孩子找最小的 if (child + 1 < n&&arr[child] > arr[child + 1]) ++child; //和当前数据做比较 //1.孩子小于当前 调整 if (arr[child] < arr[cur]) { int tmp = arr[child]; arr[child] = arr[cur]; arr[cur] = tmp; //更新位置,继续调整 cur = child; child = 2 * cur + 1; } else //2.孩子>=当前 不调整 break; }}void test(){ int arr[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); //建堆:从最后一个非叶子节点开始,向下调整 for (int i = (n - 2) / 2; i >= 0; i--) { shiftDown(arr, n, i); }}//void test()//{// int arr[] = { 10, 5, 3, 8, 7, 6 };// shiftDown(arr, sizeof(arr) / sizeof(arr[0]), 0);//}int main(){ test(); return 0;}*/
发表评论
最新留言
很好
[***.229.124.182]2025年04月15日 11时02分50秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
js求阶乘
2021-05-08
Nginx---惊群
2021-05-08
项目中常用的审计类型概述
2021-05-08
(九)实现页面底部购物车的样式
2021-05-08
python-day3 for语句完整使用
2021-05-08
基于LabVIEW的入门指南
2021-05-08
weblogic之cve-2015-4852
2021-05-08
Java注释
2021-05-08
C++ 函数重载
2021-05-08
使用mybatis-generator生成底层
2021-05-08
Mybatis【5】-- Mybatis多种增删改查那些你会了么?
2021-05-08
计算输入的一句英文语句中单词数
2021-05-08
lvs+keepalive构建高可用集群
2021-05-08
6 个 Linux 运维典型问题
2021-05-08
取消vim打开文件全是黄色方法
2021-05-08
一个系统部署多个tomcat实例
2021-05-08
HP服务器设置iLO
2021-05-08
从头实现一个WPF条形图
2021-05-08