用c语言编写哈夫曼树解码的代码并在main函数中实现输出解码后的结果
时间: 2024-03-05 20:51:17 浏览: 49
好的,以下是用C语言编写哈夫曼树解码的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义哈夫曼树节点结构体
typedef struct huffman_node {
int weight; // 权值
int parent; // 父节点索引
int left_child; // 左子节点索引
int right_child; // 右子节点索引
} huffman_node;
// 建立哈夫曼树
void create_huffman_tree(huffman_node *nodes, int n) {
int i, j, m1, m2, x1, x2;
for (i = 0; i < 2 * n - 1; i++) {
nodes[i].weight = 0;
nodes[i].parent = -1;
nodes[i].left_child = -1;
nodes[i].right_child = -1;
}
for (i = 0; i < n; i++) {
printf("请输入第%d个叶子节点的权值:", i + 1);
scanf("%d", &nodes[i].weight);
}
for (i = 0; i < n - 1; i++) {
m1 = m2 = 2147483647; // 初始化为int型最大值
x1 = x2 = 0;
for (j = 0; j < n + i; j++) {
if (nodes[j].weight < m1 && nodes[j].parent == -1) {
m2 = m1;
x2 = x1;
m1 = nodes[j].weight;
x1 = j;
} else if (nodes[j].weight < m2 && nodes[j].parent == -1) {
m2 = nodes[j].weight;
x2 = j;
}
}
nodes[x1].parent = n + i;
nodes[x2].parent = n + i;
nodes[n + i].weight = nodes[x1].weight + nodes[x2].weight;
nodes[n + i].left_child = x1;
nodes[n + i].right_child = x2;
}
}
// 哈夫曼编码
void huffman_encoding(huffman_node *nodes, int n, char **code) {
int i, j, c, p;
char *cd;
code = (char **) malloc(n * sizeof(char *));
cd = (char *) malloc(n * sizeof(char));
cd[n - 1] = '\0';
for (i = 0; i < n; i++) {
code[i] = (char *) malloc(n * sizeof(char));
p = i;
c = n - 1;
while (nodes[p].parent != -1) {
if (nodes[nodes[p].parent].left_child == p)
cd[--c] = '0';
else
cd[--c] = '1';
p = nodes[p].parent;
}
strcpy(code[i], &cd[c]);
}
free(cd);
}
// 哈夫曼解码
void huffman_decoding(huffman_node *nodes, int n, char *code, char *result) {
int i, p = 2 * n - 2;
for (i = 0; code[i] != '\0'; i++) {
if (code[i] == '0')
p = nodes[p].left_child;
else
p = nodes[p].right_child;
if (nodes[p].left_child == -1 && nodes[p].right_child == -1) { // 找到叶子节点
result[i] = (char) p;
p = 2 * n - 2; // 重新从根节点开始查找
}
}
result[i] = '\0';
}
int main() {
int n, i;
char *code, *result;
huffman_node *nodes;
printf("请输入叶子节点个数:");
scanf("%d", &n);
nodes = (huffman_node *) malloc((2 * n - 1) * sizeof(huffman_node));
create_huffman_tree(nodes, n);
huffman_encoding(nodes, n, &code);
printf("哈夫曼编码:\n");
for (i = 0; i < n; i++)
printf("%d的编码为:%s\n", i, code[i]);
result = (char *) malloc(n * sizeof(char));
printf("请输入要解码的哈夫曼编码:");
scanf("%s", result);
huffman_decoding(nodes, n, result, result);
printf("解码后的结果:%s\n", result);
for (i = 0; i < n; i++)
free(code[i]);
free(code);
free(result);
free(nodes);
return 0;
}
```
在main函数中,我们先输入叶子节点个数,然后调用`create_huffman_tree`函数建立哈夫曼树,调用`huffman_encoding`函数对每个叶子节点进行哈夫曼编码并输出,然后输入要解码的哈夫曼编码,调用`huffman_decoding`函数进行解码,并输出解码后的结果。最后释放动态分配的内存,程序结束。
阅读全文