数据结构--堆--链式存储
最小数在根节点,一层比一层大的二叉树.
#include <stdio.h> typedef int elemType; struct heap{ elemType *heap; int len; int maxsize; }; /* 1.c初始化堆*/ void initHeap(struct heap *hbt, int ms) { if(ms < 0) { printf("数组长度参数非法.\n"); system("pause"); } hbt->heap = malloc(sizeof(elemType)); if(hbt->heap == NULL) { printf("空间分配失败.\n"); system("pause"); } hbt->len = 0; hbt->maxsize = size; return; } /* 2.清除堆*/ void clearHeap(struct heap *hbt) { if(hbt->heap != NULL) { free(hbt->heap); hbt->heap = NULL; hbt->len = 0; hbt->maxsize = 0; } return; } /* 3.检查一个堆是否为空,为空返回1,否则返回0*/ int emptyHeap(struct heap *hbt) { if(hbt->heap ==NULL) { return 1; }else{ return 0; } } /* 4.向堆中插入一个元素*/ void insertHeap(struct heap *hbt, elemType x) { int i,j; if(hbt->len == hbt->maxsize) { elemType *p; p = realloc(hbt->heap, sizeof(elemType)); if(p == NULL) { printf("空间申请失败.\n"); system("pause"); } hbt->heap = p; hbt->maxsize = 2 * hbt->maxsize; } hbt->heap[hbt->len] = x; i = hbt->len; hbt->len++; while(0 != x) { j = (x-1)/2; if(x >= hbt->heap[j]) { break; } hbt->heap[j] = x; i = j; } hbt->heap[i] = x; return; } /* 5.从堆中删除元素*/ elemType deleteHeap(struct heap *hbt) { elemType x,temp; int i,j; if(0 == hbt->len) { printf("堆为空...\n"); system("pause"); } temp = hbt->heap[0]; hbt->len--; if(0 == hbt->len) { return temp; } i=0; j=2*i + 1; x = hbt->heap[hbt->len]; while(j <= hbt->len-1) { if((j < hbt->len -1) && (hbt->heap[j] > hbt->heap[j+1])) { j++; } hbt->heap[i] = hbt->heap[j]; i=j; j=2*i+1; } hbt->heap[i] = x; return temp; }