#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
int weight;
int parent,lchild,rchild;
}HTNode,*HuffmanTree;
void Select(HuffmanTree* HT,int n,int* s1,int* s2){
*s1=*s2=0;
(*HT)[0].weight=999;
for(int i=1;i<=n;i++){
if((*HT)[i].parent==0){
if((*HT)[i].weight<(*HT)[*s1].weight)
{
*s2=*s1;
*s1=i;
}
else if((*HT)[i].weight<(*HT)[*s2].weight)
*s2=i;
}
}
}
void HuffmanCoding(HuffmanTree* HT,char*** HC,int n){
if(n<=1)
return;
int m=2*n-1,s1,s2;
//初始化
(*HT)=(HuffmanTree)malloc(sizeof(HTNode)*(m+1));
for(int i=1;i<=m;i++){
(*HT)[i].parent=0;
(*HT)[i].lchild=0;
(*HT)[i].rchild=0;
}
for(int i=1;i<=n;i++){
printf("请输入第%d个字符对应的权值:",i);
scanf("%d",&((*HT)[i].weight));
}
//构建剩下的n-1个结点
for(int i=n+1;i<=m;i++){
Select(HT,i-1,&s1,&s2);
(*HT)[i].weight=(*HT)[s1].weight+(*HT)[s2].weight;
(*HT)[i].lchild=s1;
(*HT)[i].rchild=s2;
(*HT)[s1].parent=(*HT)[s2].parent=i;
}
//求哈夫曼树
(*HC)=(char**)malloc(sizeof(char*)*(n+1));
char* cd= (char*)malloc(sizeof(char)*n);
cd[n-1]='\0';
for(int i=1;i<=n;i++){
int flag=n-1;
int c=i;
int parent=(*HT)[i].parent;
while(parent!=0){
flag--;
if((*HT)[parent].lchild==c)
cd[flag]='0';
else
cd[flag]='1';
c=parent;
parent=(*HT)[parent].parent;
}
(*HC)[i]=(char*)malloc((n-flag)*sizeof(char));
strcpy((*HC)[i], &cd[flag]);
}
free(cd);
}
int main() {
HuffmanTree HT;
char** HC;
printf("请输入待编码字符个数:");
int n;
scanf("%d", &n);
HuffmanCoding(&HT, &HC, n);
for (int i = 1;i <= 2 * n - 1;i++) {
printf("%d:\t%d\t%d\t%d\t%d\n", i, HT[i].weight, HT[i].parent, HT[i].lchild, HT[i].rchild);
}
for (int i = 1;i <= n;i++) {
printf("权值为%d的哈夫曼编码:%s\n", HT[i].weight,HC[i]);
}
}
[数据结构][C语言]———哈夫曼编码
最新推荐文章于 2024-08-29 16:08:24 发布