上一篇
在计算机科学中,C语言堆数据结构是一种非常重要的树形数据结构,常用于实现优先队列、堆排序等算法。本文将带你从零开始,用通俗易懂的方式讲解堆的基本概念、分类、操作以及如何用C语言实现它。
堆(Heap)是一种特殊的完全二叉树。它满足以下性质:
由于堆是完全二叉树,我们可以使用数组来高效地存储它,而不需要使用指针构建树结构。这使得堆的实现既节省空间又便于操作。

堆支持以下核心操作:
insert:向堆中插入一个新元素。extract:移除并返回堆顶元素(最大值或最小值)。heapify:维护堆的性质,通常在插入或删除后调用。下面我们用C语言实现一个简单的最小堆。我们将使用数组来存储堆,并封装几个关键函数。
// min_heap.h#include <stdio.h>#include <stdlib.h>#define MAX_SIZE 100typedef struct { int data[MAX_SIZE]; int size;} MinHeap;void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp;}void heapify_up(MinHeap *heap, int index) { if (index == 0) return; int parent = (index - 1) / 2; if (heap->data[index] < heap->data[parent]) { swap(&heap->data[index], &heap->data[parent]); heapify_up(heap, parent); }}void insert(MinHeap *heap, int value) { if (heap->size >= MAX_SIZE) { printf("Heap is full!\n"); return; } heap->data[heap->size] = value; heap->size++; heapify_up(heap, heap->size - 1);}void heapify_down(MinHeap *heap, int index) { int left = 2 * index + 1; int right = 2 * index + 2; int smallest = index; if (left < heap->size && heap->data[left] < heap->data[smallest]) smallest = left; if (right < heap->size && heap->data[right] < heap->data[smallest]) smallest = right; if (smallest != index) { swap(&heap->data[index], &heap->data[smallest]); heapify_down(heap, smallest); }}int extract_min(MinHeap *heap) { if (heap->size <= 0) { printf("Heap is empty!\n"); return -1; } int root = heap->data[0]; heap->data[0] = heap->data[heap->size - 1]; heap->size--; heapify_down(heap, 0); return root;}
下面是一个简单的测试程序,演示了如何插入元素并提取最小值:
int main() { MinHeap heap = {0}; // 初始化堆 insert(&heap, 10); insert(&heap, 5); insert(&heap, 20); insert(&heap, 3); printf("Extracted min: %d\n", extract_min(&heap)); // 输出 3 printf("Extracted min: %d\n", extract_min(&heap)); // 输出 5 return 0;}
通过本教程,你已经掌握了C语言堆数据结构的基本原理和实现方法。无论是最小堆还是最大堆,核心思想都是通过数组模拟完全二叉树,并利用heapify操作维持堆的性质。这种结构在实际开发中应用广泛,比如任务调度、图算法(如Dijkstra)等。
希望这篇关于C语言堆操作的入门教程能帮助你打下坚实的基础!如果你有任何疑问,欢迎在评论区留言交流。
本文由主机测评网于2025-12-14发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025127718.html