输入n个叶子结点的权值构造哈夫曼树;根据哈夫曼树构造哈夫曼编码,并对密文完成解码工作。 用c语言
时间: 2023-07-08 13:50:41 浏览: 135
hafumanshu.rar_构造哈夫曼树
以下是用 C 语言实现构造哈夫曼树和哈夫曼编码以及解码的代码,其中涉及到了哈夫曼树的结构体定义、构建哈夫曼树的函数、生成哈夫曼编码的函数和解码函数。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEAF 100
typedef struct
{
int weight;
int parent;
int lchild;
int rchild;
}HuffmanNode, *HuffmanTree;
typedef struct
{
int bit[MAX_LEAF];
int start;
}HuffmanCode;
void CreateHuffmanTree(HuffmanTree *HT, int n)
{
int i, min1, min2;
*HT = (HuffmanTree)malloc((2 * n - 1) * sizeof(HuffmanNode));
for (i = 0; i < n; ++i)
{
scanf("%d", &((*HT)[i].weight));
(*HT)[i].parent = -1;
(*HT)[i].lchild = -1;
(*HT)[i].rchild = -1;
}
for (i = n; i < 2 * n - 1; ++i)
{
(*HT)[i].weight = 0;
(*HT)[i].parent = -1;
(*HT)[i].lchild = -1;
(*HT)[i].rchild = -1;
}
for (i = n; i < 2 * n - 1; ++i)
{
min1 = min2 = 32767;
int j;
for (j = 0; j < i; ++j)
{
if ((*HT)[j].parent == -1)
{
if ((*HT)[j].weight < min1)
{
min2 = min1;
min1 = (*HT)[j].weight;
(*HT)[i].lchild = j;
}
else if ((*HT)[j].weight < min2)
{
min2 = (*HT)[j].weight;
(*HT)[i].rchild = j;
}
}
}
(*HT)[i].weight = min1 + min2;
(*HT)[(*HT)[i].lchild].parent = i;
(*HT)[(*HT)[i].rchild].parent = i;
}
}
void CreateHuffmanCode(HuffmanTree HT, HuffmanCode *HC, int n)
{
int i, j, c, p;
for (i = 0; i < n; ++i)
{
HC[i].start = n;
c = i;
p = HT[i].parent;
while (p != -1)
{
if (HT[p].lchild == c)
HC[i].bit[HC[i].start--] = 0;
else
HC[i].bit[HC[i].start--] = 1;
c = p;
p = HT[p].parent;
}
HC[i].start++;
}
}
void HuffmanDecode(HuffmanTree HT, char *code, char *result)
{
int i, j, p = 2 * strlen(code) - 2;
for (i = 0; i < strlen(code); ++i)
{
if (code[i] == '0')
p = HT[p].lchild;
else
p = HT[p].rchild;
if (HT[p].lchild == -1 && HT[p].rchild == -1)
{
result[i] = p;
p = 2 * strlen(code) - 2;
}
}
result[i] = '\0';
}
int main()
{
int n, i;
char code[MAX_LEAF], result[MAX_LEAF];
HuffmanTree HT;
HuffmanCode HC[MAX_LEAF];
printf("请输入叶子结点的个数:");
scanf("%d", &n);
printf("请输入各个叶子结点的权重:");
CreateHuffmanTree(&HT, n);
CreateHuffmanCode(HT, HC, n);
printf("请输入要编码的字符串:");
scanf("%s", code);
for (i = 0; i < strlen(code); ++i)
{
int j;
for (j = 0; j < n; ++j)
{
if (code[i] == j + 'a')
{
int k;
for (k = HC[j].start; k <= n; ++k)
printf("%d", HC[j].bit[k]);
}
}
}
printf("\n");
printf("请输入要解码的编码:");
scanf("%s", code);
HuffmanDecode(HT, code, result);
printf("解码结果为:%s\n", result);
return 0;
}
```
上述代码中定义了 `HuffmanNode` 结构体用于存储哈夫曼树结点的信息, `HuffmanTree` 是一个指向 `HuffmanNode` 结构体的指针,用于存储哈夫曼树, `HuffmanCode` 结构体用于存储哈夫曼编码信息。
`CreateHuffmanTree` 函数用于构建哈夫曼树, `CreateHuffmanCode` 函数用于生成哈夫曼编码, `HuffmanDecode` 函数用于解码。在 `main` 函数中,首先输入叶子结点的个数和权重,然后生成哈夫曼树并生成哈夫曼编码,接着输入要编码的字符串,输出编码结果;最后输入要解码的编码,输出解码结果。
阅读全文