马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<stdlib.h>
#define MAXNUM 50
typedef struct
{
char data;
int weight;
int parent;
int leftchild;
int rightchild;
}HuffNode;
typedef struct
{
char cd[MAXNUM];
int start;
}HuffCode;
int HaffmanCreat(HuffNode *ht)
{
int i,k,n,min1,min2,lnode,rnode;
printf("请输入元素个数:");
scanf("%d",&n);
for(i=1;i<=n;i++) //输入结点值和信息
{
getchar();
printf("第%d个元素的=>\n\t结点值:",i);
scanf("%c",&ht[i].data);
printf("\t权重:");
scanf("%d",&ht[i].weight);
}
for(i=1;i<=2*n-1;i++) //对数组初始化
{
ht[i].parent=0;
ht[i].leftchild=0;
ht[i].rightchild=0;
}
for(i=n+1;i<=2*n-1;i++)
{
min1=min2=32767;
lnode=1;
rnode=1;
for(k=1;k<=i-1;k++) //从数组中找权值最小的两个结点
if(ht[k].parent==0) //在尚未参与构造的结点中找
if(ht[k].weight<min1)
{
min2=min1;
rnode=lnode;
min1=ht[k].weight;
lnode=k;
}
else if(ht[k].weight<min2)
{
min2=ht[k].weight;
rnode=k;
}
ht[i].weight=min1+min2;
ht[i].leftchild=lnode;
ht[i].rightchild=rnode;
ht[lnode].parent=i;
ht[rnode].parent=i;
}
printf("哈夫曼树已成功建立!\n");
return n;
}
void PrintBTNode(HuffNode *hf, int index,int n) //横向输出
{
if(hf[index].leftchild!=0||hf[index].rightchild!=0)
{
PrintBTNode(hf,hf[index].rightchild,n+1);
if(n!=0)
{
for(int i=0;i<4*(n-1);i++)
{
printf("%s"," ");
}
printf("%s","---");
}
printf("o\n");
PrintBTNode(hf,hf[index].leftchild,n+1);
}
else
{
if(n!=0)
{
for(int i=0;i<4*(n-1);i++)
{
printf("%s"," ");
}
printf("%s","---");
}
printf("%c \n",hf[index].data);
}
}
void Encoding(HuffNode ht[],HuffCode hcd[],int n) //哈夫曼编码
{
HuffCode d;
int i,k,f,c;
for(i=1;i<=n;i++)
{
d.start=n+1;
c=i;
f=ht[i].parent;
while(f!=0)
{
if(ht[f].leftchild==c)
d.cd[--d.start]='0';
else
d.cd[--d.start]='1';
c=f;
f=ht[f].parent;
}
hcd[i]=d;
}
printf("输出哈夫曼编码:\n");
for(i=1;i<=n;i++)
{
printf("%c:",ht[i].data);
for(k=hcd[i].start;k<=n;k++)
printf("%c",hcd[i].cd[k]);
printf("\n");
}
}
int main()
{
HuffNode *ht;
HuffCode *hcd;
int n;
ht=(HuffNode *)malloc(sizeof(HuffNode));
hcd=(HuffCode *)malloc(sizeof(HuffCode));
n=HaffmanCreat(ht);
PrintBTNode(ht,2*n-1,0);
Encoding(ht,hcd,n);
}
|