C语言实现输入5个字母和小数权值,输出对应的哈夫曼编码
时间: 2024-02-28 22:55:49 浏览: 61
使用c语言实现哈夫曼编码
以下是C语言实现输入5个字母和小数权值,输出对应的哈夫曼编码的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
typedef struct {
char ch;
double weight;
char code[MAX_LEN];
} HuffNode;
void HuffmanCoding(HuffNode *node, int n) {
int i, j, k;
double min1, min2;
int x1, x2;
char *cd;
for (i = 0; i < n; i++) {
node[i].code[0] = '\0';
}
for (i = 0; i < n - 1; i++) {
min1 = min2 = 1e9;
x1 = x2 = 0;
for (j = 0; j < n + i; j++) {
if (node[j].weight < min1 && node[j].code[0] == '\0') {
min2 = min1;
x2 = x1;
min1 = node[j].weight;
x1 = j;
} else if (node[j].weight < min2 && node[j].code[0] == '\0') {
min2 = node[j].weight;
x2 = j;
}
}
node[x1].code[strlen(node[x1].code)] = '0';
node[x2].code[strlen(node[x2].code)] = '1';
strcat(node[x1].code, node[x2].code);
node[x1].weight = min1 + min2;
}
}
int main() {
int n = 5;
HuffNode node[n];
int i;
printf("请输入5个字母和对应的小数权值:\n");
for (i = 0; i < n; i++) {
scanf("%c %lf", &node[i].ch, &node[i].weight);
getchar();
}
HuffmanCoding(node, n);
printf("哈夫曼编码:\n");
for (i = 0; i < n; i++) {
printf("%c: %s\n", node[i].ch, node[i].code);
}
return 0;
}
```
运行程序后,输入5个字母和对应的小数权值,即可输出对应的哈夫曼编码。
阅读全文