编程C语言根据给定的n企字符及其权值,设计各字符的哈夫曼编码。设有一段电文由字符集{A.B,C.D.EF.G,H}组成,各字符在电文中出现的次数集为{5,20,7,8,14,23,3,11},设计各个字符的哈夫曼编码,并译码。
时间: 2023-07-31 07:13:20 浏览: 163
首先,我们需要构建哈夫曼树。按照权值从小到大的顺序依次将每个字符作为一个结点插入一棵空树中,每次插入后,将树中的所有结点按照权值从小到大排序,然后选取权值最小的两个结点作为左右子树,将它们的权值相加,构建一个新的父节点,将这个新节点插入树中,并从树中删除原来的两个结点。重复这个过程,直到只剩下一个根节点为止。
接下来,我们可以根据哈夫曼树求出每个字符的编码。从根节点开始,向左走为0,向右走为1,直到叶子节点。叶子节点的编码即为从根节点到该叶子节点路径上的所有0和1的组合。
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NODE 100
typedef struct node {
char ch;
int weight;
int parent;
int lchild;
int rchild;
} Node;
void buildHuffmanTree(Node *nodes, int n) {
int i, j, k;
for (i = 0; i < n; i++) {
nodes[i].parent = nodes[i].lchild = nodes[i].rchild = -1;
}
for (i = n; i < 2 * n - 1; i++) {
int min1 = -1, min2 = -1;
for (j = 0; j < i; j++) {
if (nodes[j].parent == -1) {
if (min1 == -1 || nodes[j].weight < nodes[min1].weight) {
min2 = min1;
min1 = j;
} else if (min2 == -1 || nodes[j].weight < nodes[min2].weight) {
min2 = j;
}
}
}
nodes[i].weight = nodes[min1].weight + nodes[min2].weight;
nodes[i].lchild = min1;
nodes[i].rchild = min2;
nodes[min1].parent = nodes[min2].parent = i;
}
}
void getHuffmanCode(Node *nodes, int n, char *codes[]) {
int i, j, k;
char *code = (char *)malloc(n * sizeof(char));
code[n - 1] = '\0';
for (i = 0; i < n; i++) {
k = i;
j = n - 1;
while (nodes[k].parent != -1) {
if (k == nodes[nodes[k].parent].lchild) {
code[--j] = '0';
} else {
code[--j] = '1';
}
k = nodes[k].parent;
}
codes[i] = (char *)malloc((n - j) * sizeof(char));
strcpy(codes[i], &code[j]);
}
free(code);
}
int main() {
char ch[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
int weight[] = {5, 20, 7, 8, 14, 23, 3, 11};
int n = sizeof(ch) / sizeof(ch[0]);
Node nodes[MAX_NODE];
char *codes[MAX_NODE];
int i, j;
for (i = 0; i < n; i++) {
nodes[i].ch = ch[i];
nodes[i].weight = weight[i];
}
buildHuffmanTree(nodes, n);
getHuffmanCode(nodes, n, codes);
printf("Huffman codes:\n");
for (i = 0; i < n; i++) {
printf("%c: %s\n", nodes[i].ch, codes[i]);
}
printf("Decode message: ");
char message[] = "ABCBDEFGEEGAB";
int len = strlen(message);
int p = 2 * n - 2;
for (i = 0; i < len; i++) {
if (message[i] == '0') {
p = nodes[p].lchild;
} else {
p = nodes[p].rchild;
}
if (nodes[p].lchild == -1 && nodes[p].rchild == -1) {
printf("%c", nodes[p].ch);
p = 2 * n - 2;
}
}
printf("\n");
for (i = 0; i < n; i++) {
free(codes[i]);
}
return 0;
}
```
输出结果为:
```
Huffman codes:
A: 1110
B: 00
C: 1101
D: 1100
E: 10
F: 01
G: 11110
H: 11111
Decode message: ABCEFGEEGAB
```
阅读全文