编译成功
/* Note:Your choice is C IDE */
#include
#include
#define N 15
#define M 2*N-1
typedef struct
{float weight;
unsigned int parent,lchild,rchild;
}HTNode;
typedef struct
{
char data;
float weight;
char code[N];
}HTCode;
main()
{
int i,m,n,w[N+1];
float l=0.0;
HTNode ht[M+1];
HTCode hc[N+1];
Init (hc,&n);
HuffmanCoding (ht,hc,n);
for(i=1;i<=n;i++)
printf("\nThe code of '%c' is :%s",hc[i].data,hc[i].code);
for(i=1;i<=n;i++)
{l+=strlen (hc[i].code)*hc[i].weight;}
/*l=l/n;*/
printf("\n The average length of the Huffman coding is %f",l);
}
Init (HTCode hc[],int *n)
{
int i;
printf("\n input n=");
scanf("%d",&(*n));
fflush(stdin);
printf("\n input %d character \n",*n);
for(i=1;i<=*n;i++)
{printf("\n the %d character is:",i);
scanf("%c",&(hc[i].data));
fflush(stdin);
}
for(i=1;i<=*n;i++)
{printf("\n the %d character weight is:",i);
scanf("%f",&(hc[i].weight));}
}
HuffmanCoding (HTNode ht[],HTCode hc[],int n)
{
char cd[N];
int i,j,m,c,f,s1,s2,start;
m=2*n-1; /*2n-1个节点*/
for(i=1;i<=m;i++) /*初始化节点,1~n个原始节点有值*/
{
if(i<=n) ht[i].weight=hc[i].weight;
else ht[i].weight=0.0;
ht[i].parent=ht[i].lchild=ht[i].rchild=0;
}
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;
}
for(i=1;i<=m;i++)
{
printf("\n the %d charactor weight is %f:",i,ht[i].weight);
printf("\n the %d charactor lchild is %d:",i,ht[i].lchild);
printf("\n the %d charactor rchild is %d:",i,ht[i].rchild);
printf("\n the %d charactor parent is %d:",i,ht[i].parent);
}
for(i=0;i
cd[i]="";
cd[n-1]='\0'; /*编码初始化*/
for(i=1;i<=n;i++)
{
start=n-1;
for(c=i,f=ht[i].parent;f;f=ht[f].parent) /*遍历到父节点*/
if(ht[f].lchild==c)
cd[--start]='0';
else
cd[--start]='1';
strcpy(hc[i].code,&cd[start]);
}
}
Select(HTNode ht[],int k,int *s1,int *s2)
{
int i;
for(i=1;i<=k;i++)
{
if(ht[i].parent==0)
{*s1=i;
break;}
}
for(i=1;i<=k;i++)
if(ht[i].parent==0&&ht[i].weight
*s1=i;
for(i=1;i<=k;i++)
{if(ht[i].parent==0&&i!=*s1)
{*s2=i;
break;}
}
for(i=1;i<=k;i++)
if(ht[i].parent==0&&i!=*s1&&ht[i].weight
*s2=i;
printf("\n This is *s1:%d\n",*s1);
printf("\n This is *s2:%d\n",*s2);
}