#include
#include
#define maxw 1000
#define N 100
#define nmax 27
typedef struct node
{
char data;
int weight;
int parent;
int lchild;
int rchild;
}HFnode;
typedef struct
{
char cd[N];
int start;
}Hcode;
void creatH(HFnode h[], int n)
{
int i,k;
int m1,m2;
int x1,x2;
for(i=0;i<2*n-1;i++)
{
h[i].parent=h[i].lchild=h[i].rchild=-1;
}
for(i=n;i<2*n-1;i++)
{
m1=m2=maxw;
x1=x2=-1;
for(k=1;i
{
if(h[k].parent=-1&&h[k].weight
{
m2=m1;
m1=h[k].weight;
x2=x1;
x1=i;
}
else if(h[k].parent=-1&&h[k].weight
{
m2=h[k].weight;
x2=k;
}
}
h[i].weight=h[x1].weight+h[x2].weight;
h[i].lchild=x1;h[i].rchild=x2;
h[x1].parent=h[x2].parent=i;
}
}
void creatHcode(HFnode ht[],Hcode hcd[],int n)
{
int i,f,c,j;
Hcode hc;
for(i=0;i
{
hc.start=n;
c=i;
f=ht[i].parent;
while(f!=-1)
{
if(ht[f].lchild==c)
hc.cd[hc.start--]='0';
else
hc.cd[hc.start--]='1';
c=f;f=ht[f].parent;
}
hc.start++;
hcd[i]=hc;
}
}
int main()
{
int n,i;
HFnode h[nmax];
Hcode hcode[N];
printf("哈夫曼编码系统 \n *************");
printf("输入节点的个数:");
scanf("%d",&n);
for(i=0;i
{
printf("请输入第%d个元素的节点值和权值:",i);
scanf("%d%d",&h[i].data,&h[i].weight);
}
creatH(h,n);
creatHcode(h,hcode,n);
return 0;
}
一点注释都没有吗?