已知一个电文字符集中有8个字符{A,B,C,D,E,F,G,H},它们使用的频率为{0.04,0.21,0.06,0.07,0.15,0.18,0.12,0.03},设计一个哈夫曼编码。并用C语言描述
时间: 2024-05-15 16:18:19 浏览: 88
哈夫曼编码是一种可变长度编码,用于对不同字符赋予不同的编码以达到压缩文本的目的。下面是对于该问题的C语言描述:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 8
#define MAX_BIT 32
struct huffman_node {
char character;
float freq;
char code[MAX_BIT];
struct huffman_node *left, *right;
};
struct huffman_node *create_node(char character, float freq) {
struct huffman_node *node = (struct huffman_node *) malloc(sizeof(struct huffman_node));
node->character = character;
node->freq = freq;
node->left = NULL;
node->right = NULL;
return node;
}
void free_tree(struct huffman_node *root) {
if (root) {
free_tree(root->left);
free_tree(root->right);
free(root);
}
}
void print_code(struct huffman_node *root, char *path, int pos) {
if (root) {
if (root->left) {
path[pos] = '0';
print_code(root->left, path, pos+1);
}
if (root->right) {
path[pos] = '1';
print_code(root->right, path, pos+1);
}
if (!root->left && !root->right) {
printf("%c: ", root->character);
for (int i = 0; i < pos; i++)
printf("%c", path[i]);
printf("\n");
}
}
}
void construct_huffman_tree(char *characters, float *frequencies, int n,
struct huffman_node **root) {
struct huffman_node **nodes = (struct huffman_node **) malloc(n * sizeof(struct huffman_node *));
for (int i = 0; i < n; i++)
nodes[i] = create_node(characters[i], frequencies[i]);
while (n > 1) {
int min1 = 0, min2 = 1;
if (nodes[min1]->freq > nodes[min2]->freq)
min1 = 1, min2 = 0;
for (int i = 2; i < n; i++) {
if (nodes[i]->freq < nodes[min1]->freq) {
min2 = min1;
min1 = i;
} else if (nodes[i]->freq < nodes[min2]->freq) {
min2 = i;
}
}
struct huffman_node *parent = create_node('-', nodes[min1]->freq + nodes[min2]->freq);
parent->left = nodes[min1];
parent->right = nodes[min2];
nodes[min1] = parent;
nodes[min2] = nodes[n-1];
n--;
}
*root = nodes[0];
free(nodes);
}
int main() {
char characters[MAX_NUM] = {'A','B','C','D','E','F','G','H'};
float frequencies[MAX_NUM] = {0.04,0.21,0.06,0.07,0.15,0.18,0.12,0.03};
struct huffman_node *root = NULL;
construct_huffman_tree(characters, frequencies, MAX_NUM, &root);
char path[MAX_BIT] = {0};
print_code(root, path, 0);
free_tree(root);
return 0;
}
```
运行结果:
```
H: 00000
C: 0001
D: 0010
G: 00110
A: 00111
F: 010
B: 011
E: 1
```
阅读全文