堆的基本操作源代码bing
Posted 鸟随二月
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了堆的基本操作源代码bing相关的知识,希望对你有一定的参考价值。
Heap.h
#pragma once
#include<stdio.h>
#include<assert.h>
#include<malloc.h>
typedef int type;
typedef type(*function)(type, type);
typedef struct Heap
int size = 0;
int capcity;
type* array;
function fun;
Heap;
//初始化
void heapCreate(Heap *heap, type *array, int size, function fun);
//堆插入
void push(Heap*heap, type);
//删堆顶
type pop(Heap* heap);
void swap(type*a, type*b);
//向下调整
void adjustDown(Heap* heap, int root);
//向上调整
void adjustUp(Heap* heap);
//堆删除
void heapDestory(Heap* heap);
int isEmpty(Heap *heap);
int isFull(Heap *heap);
//返堆顶
int top(Heap *heap);
void swap(type*a, type*b)
int temp = *a;
*a = *b;
*b = temp;
void heapCreate(Heap *heap, type *array, int size, function fun)
assert(heap != NULL);
heap->array = (type*)malloc(2*size * sizeof(type));
assert(heap->array != NULL);
memcpy(heap->array, array,size*sizeof(type));
heap->size = size;
heap->capcity = 2 * size;
heap->fun = fun;
for (int i = (size-2)/2; i >=0 ; i--)
adjustDown(heap, i);
void push(Heap*heap, type data)
if (isFull(heap))
heap->array = (type*)realloc(heap->array, 2 * heap->capcity * sizeof(type));
assert(heap->array != NULL);
heap->capcity *= 2;
heap->array[heap->size++] = data;
adjustUp(heap);
type pop(Heap* heap)
if (isEmpty(heap))
printf("该堆为空");
return -1;
type res = heap->array[0];
heap->array[0] = heap->array[--heap->size];
adjustDown(heap, 0);
return res;
void adjustDown(Heap* heap, int root)
int child = 2 * root + 1;
while (child < heap->size)
if (child+1<heap->size&&heap->fun(heap->array[child], heap->array[child + 1]))
child +=1;
if (heap->fun(heap->array[root],heap->array[child]))
swap(&(heap->array[root]), &(heap->array[child]));
else
break;
root = child;
child = 2 * root + 1;
void adjustUp(Heap* heap)
int child = heap->size - 1;
if (child<=0)
return;
int parent = (child - 1) / 2;
while (child > 0)
if (heap->fun(heap->array[parent], heap->array[child]))
swap(&heap->array[parent], &heap->array[child]);
else
break;
child = parent;
parent = (child - 1) / 2;
void heapDestory(Heap* heap)
free(heap->array);
free(heap);
int isEmpty(Heap *heap)
return heap->size == 0;
int isFull(Heap *heap)
return heap->size == heap->capcity;
int top(Heap *heap)
return heap->array[0];
测试文件
#include <stdio.h>
#include<Windows.h>
#include "Heap.h"
int big(int a, int b)
return a>b;
int main()
Heap heap;
type a[5] = 5,4,3,2,1 ;
heapCreate(&heap, a, 5, big);
pop(&heap);
printf("%d",heap.array[0]);
system("pause");
以上是关于堆的基本操作源代码bing的主要内容,如果未能解决你的问题,请参考以下文章