C语言采用一维数组完成哈夫曼编码HuffmanTree HT,HuffmanCode &HC添加注释 任务:根据给定的若干权值来构造哈夫曼树,实现对应的哈夫曼编码以及译码。 功能要求: 1)按传输文本中字符的个数以及字符的频率来建立并输出哈夫曼树的存储结构; 2)设计并输出各字符对应的哈夫曼编码; 3)将传输的文本转换成对应的哈夫曼编码01序列; 将哈夫曼编码01序列翻译成原来的文本字符。
时间: 2023-07-19 12:46:11 浏览: 152
C语言实现Huffman树,Huffman编码
5星 · 资源好评率100%
以下是C语言实现哈夫曼编码的代码,其中包含注释:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1000 // 定义最大编码长度
typedef struct {
int weight; // 权值
int parent, lchild, rchild; // 双亲和左右孩子结点
} HTNode, *HuffmanTree;
typedef char **HuffmanCode;
void Select(HuffmanTree HT, int n, int *s1, int *s2) {
// 在前n个结点中选择权值最小的两个结点s1和s2
int i, min;
for (i = 1; i <= n; i++) {
if (HT[i].parent == 0) {
min = i;
break;
}
}
for (i = 1; i <= n; i++) {
if (HT[i].parent == 0 && HT[i].weight < HT[min].weight) {
min = i;
}
}
*s1 = min;
for (i = 1; i <= n; i++) {
if (HT[i].parent == 0 && i != *s1) {
min = i;
break;
}
}
for (i = 1; i <= n; i++) {
if (HT[i].parent == 0 && HT[i].weight < HT[min].weight && i != *s1) {
min = i;
}
}
*s2 = min;
}
void CreateHuffmanTree(HuffmanTree *HT, int n) {
// 由n个权值为w的结点构建哈夫曼树HT
if (n <= 1) {
return;
}
int m = 2 * n - 1;
*HT = (HuffmanTree) malloc((m + 1) * sizeof(HTNode));
int i;
for (i = 1; i <= m; i++) {
(*HT)[i].parent = 0;
(*HT)[i].lchild = 0;
(*HT)[i].rchild = 0;
}
for (i = 1; i <= n; i++) {
scanf("%d", &((*HT)[i].weight));
}
int s1, s2;
for (i = n + 1; i <= m; i++) {
Select(*HT, i - 1, &s1, &s2);
(*HT)[s1].parent = i;
(*HT)[s2].parent = i;
(*HT)[i].lchild = s1;
(*HT)[i].rchild = s2;
(*HT)[i].weight = (*HT)[s1].weight + (*HT)[s2].weight;
}
}
void CreateHuffmanCode(HuffmanTree HT, HuffmanCode *HC, int n) {
// 根据哈夫曼树HT求出n个字符的哈夫曼编码HC
*HC = (HuffmanCode) malloc((n + 1) * sizeof(char *));
char *cd = (char *) malloc(n * sizeof(char));
cd[n - 1] = '\0';
int i, c, f;
for (i = 1; i <= n; i++) {
int start = n - 1;
for (c = i, f = HT[i].parent; f != 0; c = f, f = HT[f].parent) {
if (HT[f].lchild == c) {
cd[--start] = '0';
} else {
cd[--start] = '1';
}
}
(*HC)[i] = (char *) malloc((n - start) * sizeof(char));
strcpy((*HC)[i], &cd[start]);
}
free(cd);
}
void HuffmanCoding(HuffmanTree HT, HuffmanCode HC, int n) {
// 输入n个字符的权值,建立哈夫曼树HT,并求出n个字符的哈夫曼编码HC
CreateHuffmanTree(&HT, n);
CreateHuffmanCode(HT, &HC, n);
}
void HuffmanDecoding(HuffmanTree HT, int n) {
// 将01序列翻译成原来的文本字符
printf("请输入01序列:\n");
char str[MAX];
scanf("%s", str);
int i, c = 2 * n - 1;
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == '0') {
c = HT[c].lchild;
} else {
c = HT[c].rchild;
}
if (HT[c].lchild == 0 && HT[c].rchild == 0) {
printf("%d", c);
c = 2 * n - 1;
}
}
}
int main() {
int n;
printf("请输入字符的个数n:\n");
scanf("%d", &n);
HuffmanTree HT;
HuffmanCode HC;
HuffmanCoding(HT, HC, n);
int i;
printf("各字符的哈夫曼编码如下:\n");
for (i = 1; i <= n; i++) {
printf("%d %s\n", i, HC[i]);
}
HuffmanDecoding(HT, n);
return 0;
}
```
以上是C语言实现哈夫曼编码的代码,可以根据输入的字符权值构建哈夫曼树,并输出各字符对应的哈夫曼编码。同时,可以将传输的文本转换成对应的哈夫曼编码01序列,并将哈夫曼编码01序列翻译成原来的文本字符。
阅读全文