写出c语言构造哈夫曼树的代码
时间: 2023-09-17 13:11:25 浏览: 86
哈夫曼树的代码
下面是 C 语言构造哈夫曼树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODE_COUNT 256 // 字符集大小为 256
typedef struct Node {
char c;
int freq;
struct Node *left, *right;
} Node;
typedef struct MinHeap {
int count;
Node **array;
} MinHeap;
Node *new_node(char c, int freq, Node *left, Node *right) {
Node *node = (Node *)malloc(sizeof(Node));
node->c = c;
node->freq = freq;
node->left = left;
node->right = right;
return node;
}
MinHeap *create_min_heap(int size) {
MinHeap *min_heap = (MinHeap *)malloc(sizeof(MinHeap));
min_heap->count = 0;
min_heap->array = (Node **)malloc(size * sizeof(Node *));
return min_heap;
}
void swap(Node **l, Node **r) {
Node *temp = *l;
*l = *r, *r = temp;
}
void min_heapify(MinHeap *min_heap, int index) {
int min = index, left = index * 2 + 1, right = index * 2 + 2;
if (left < min_heap->count && min_heap->array[min]->freq > min_heap->array[left]->freq)
min = left;
if (right < min_heap->count && min_heap->array[min]->freq > min_heap->array[right]->freq)
min = right;
if (min != index) {
swap(&min_heap->array[min], &min_heap->array[index]);
min_heapify(min_heap, min);
}
}
int is_single_node(MinHeap *min_heap) {
return min_heap->count == 1;
}
Node *extract_min(MinHeap *min_heap) {
Node *node = min_heap->array[0];
min_heap->array[0] = min_heap->array[min_heap->count - 1];
--min_heap->count;
min_heapify(min_heap, 0);
return node;
}
void insert(MinHeap *min_heap, Node *node) {
++min_heap->count;
int index = min_heap->count - 1;
while (index > 0 && node->freq < min_heap->array[(index - 1) / 2]->freq) {
min_heap->array[index] = min_heap->array[(index - 1) / 2];
index = (index - 1) / 2;
}
min_heap->array[index] = node;
}
void build_min_heap_from_freqs(int freqs[]) {
MinHeap *min_heap = create_min_heap(MAX_NODE_COUNT);
for (int i = 0; i < MAX_NODE_COUNT; ++i) {
if (freqs[i] > 0) {
Node *node = new_node((char)i, freqs[i], NULL, NULL);
insert(min_heap, node);
}
}
while (!is_single_node(min_heap)) {
Node *left = extract_min(min_heap), *right = extract_min(min_heap);
Node *node = new_node('\0', left->freq + right->freq, left, right);
insert(min_heap, node);
}
Node *root = extract_min(min_heap);
}
void build_min_heap_from_file(char *filename) {
FILE *fp = fopen(filename, "r");
if (!fp) {
fprintf(stderr, "Error: failed to open file `%s`\n", filename);
exit(1);
}
int freqs[MAX_NODE_COUNT] = {};
int c;
while ((c = fgetc(fp)) != EOF) {
++freqs[c];
}
fclose(fp);
build_min_heap_from_freqs(freqs);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return 1;
}
build_min_heap_from_file(argv[1]);
return 0;
}
```
阅读全文