帮忙看看我写的代码哪里不对
建立 exp4-2.cpp 文件,实现哈夫曼编码功能,要求如下:
a) 输入字符及字符出现次数;
b) 参考课本哈夫曼树建立算法建立哈夫曼树;
c) 输出每个字符的哈夫曼编码。
#include
#define N 110
#define M 2*N-1
typedef struct
{
char data;
double weight;
int parent;
int lchild;
int rchild;
}HTNode;
typedef struct
{
char cd[N];
int start;
}HCode;
void CreateHT(HTNode ht[],int n)
{
int i,k,lnode,rnode;
double min1,min2;
for(int i=0;i<2*n-1;i++)
{
ht[i].parent=ht[i].lchild=ht[i].rchild=-1;
}
for(int i=n;i<=2*n-2;i++)
{
min1=min2=32767;
lnode=rnode=-1;
for(k=0;k<=i-1;k++)
{
if(ht[k].parent==-1)
{
if(ht[k].weightmin2=min1;rnode=lnode;
min1=ht[k].weight;rnode=k;
}
else if(ht[k].weightmin2=ht[k].weight;rnode=k;
}
}
}
ht[i].weight=ht[lnode].weight+ht[rnode].weight;
ht[i].lchild=lnode;ht[i].rchild=rnode;
ht[lnode].parent=i;ht[rnode].parent=i;
}
}
void CreateHCode(HTNode ht[],HCode hcd[],int n)
{
int i,f,c;
HCode hc;
for(int i=0;istart=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;
}
}
void DispHCode(HTNode ht[],HCode hcd[],int n)
{
printf("输出哈夫曼编码:\n");
for(int i=0;i"%d:",ht[i].data);
for(int j=hcd[i].start;j<=n;j++)
{
printf("%c",hcd[i].cd[j]);
}
printf("\n");
}
}
int main()
{
HTNode ht[M];
HCode hcd[N];
char a;
int b;
int i=0;
while(scanf("%c %d",&a,&b)==1)
{
ht[i].data=a;
ht[i].weight=b;
i++;
}
CreateHT(ht,i);
CreateHCode(ht,hcd,i);
DispHCode(ht,hcd,i);
}