赫夫曼树编码的实现
自己看书(赫夫曼树),觉得懂了便自己动手敲一个书上的题目,可是实现不了,真的不知道哪错了。求搞手指教。下面是我的代码:#include<stdio.h>
#include<string.h>
typedef struct
{
unsigned int weight;
unsigned int parent,lchild,rchild;
}HTNODE,*huffmantree;
typedef char * *huffmancode;
void select(huffmantree HT,int n,int *s1,int *s2);
void huffmancoding(huffmantree HT,huffmancode HC,int *w,int n);
int main()
{
huffmantree HT;
huffmancode HC;
int w[8];
int i,m,n;
for(i=0;i<8;i++)
{
printf("请输入第%d个编码数\n",i+1);
scanf("%d",&w[i]);
}
for(i=0;i<8;i++)
{
printf("%d\n",w[i]);
}
printf("niah\n");
huffmancoding(HT,HC,w,8);
printf("输出的编码是\n");
for(n=0;n<9;n++)
{
printf("%s\n",HC[n]);
}
}
void select(huffmantree HT,int n,int *s1,int *s2)
{
int i,i1,i2,i3;
int min1,min2;
min1=min2=32767;
for(i=1;i<=n;i++)
{
if(HT[i].parent==0)
{
if(HT[i].weight<min1)
{
min1=HT[i].weight;
*s1=i;
}
}
else
{
continue;
}
}
for(i=1;i<=n;i++)
{
if(HT[i].parent==0)
{
if(min1<HT[i].weight<min2)
{
min2=HT[i].weight;
*s2=i;
}
}
else
{
continue;
}
}
}
void huffmancoding(huffmantree HT,huffmancode HC,int *w,int n)
{
int m,i,x,start,c,f;
huffmantree p;
int *s1,*s2;
char *cd;
x=0;
s1=s2=&x;
if(n<=1)
{
return;
}
printf("dazhele\n");
m=2*n-1;
HT=(huffmantree)malloc((m+1)*sizeof(HTNODE));
for(p=HT,i=1;i<=n;++i,++p,++w)
{
p[i].weight=w[i-1];
printf("dazhele1\n");
}
for(;i<m;++i)
{
p[i].weight=0;
printf("dazhele2\n");
}
for(i=n+1;i<=m;++i)
{
printf("dazhele3\n");
select(HT,i-1,s1,s2);
printf("dazhele4\n");
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;
}
printf("dazhele5\n");
HC=(huffmancode)malloc((n+1)*sizeof(char *));
cd=(char *)malloc(n*sizeof(char));
cd[n-1]="\0";
printf("dazhele6\n");
for(i=1;i<=n;++i)
{
printf("dazhele7\n");
start=n-1;
for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)
{
printf("dazhele8\n");
if(HT[f].lchild==c)
{
printf("dazhele9\n");
cd[--start]="0";
printf("dazhele11\n");
}
else
{
printf("dazhele12\n");
cd[--start]="1";
printf("dazhele13\n");
}
}
printf("dazhele9\n");
HC[i]=(char *)malloc((n-start)*sizeof(char));
strcpy(HC[i],&cd[start]);
}
free(cd);
}
谢谢!!!!