关于哈夫曼编码的,纠错,怎么输不出每个字符的哈夫曼码喃?双重指针太纠结了。。。。
//帮忙找下问题。不甚感激啊!!!#include"stdio.h"
#include"stdlib.h"
#include"string.h"
typedef struct
{
int weight;
int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char * *HuffmanCode;
void Select(HuffmanTree HT,int n,int *s1,int *s2)
{
HuffmanTree p;
int i,j;
for(i=1;i<=n;i++)
{
if(HT[i].parent==0)
{
*s1=i;
break;
}
}
for(j=i+1;j<=n;j++)
{
p=&HT[j];
if(HT[*s1].weight>p->weight&&p->parent==0)
*s1=j;
}
for(i=1;i<=n;i++)
{
if(HT[i].parent==0&&i!=*s1)
{
*s2=i;
break;
}
}
for(j=i+1;j<=n;j++)
{
p=&HT[j];
if(HT[*s2].weight>p->weight&&j!=*s1&&p->parent==0)
*s2=j;
}
}
void HuffmanCoding(HuffmanTree *HT,HuffmanCode *HC,int array[],int n)
{
int m,i,j,s1,s2,f,c,start;
HuffmanTree p;
char* cd;
if(n<=1)
return;
m=2*n-1;
*HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));
for(p=(*HT)+1,i=1,j=0;i<=n;i++,p++,j++)
{
p->weight=array[j];
p->parent=0;
p->lchild=0;
p->rchild=0;
}
for(;i<=m;i++,p++)
{
p->parent=0;
p->lchild=0;
p->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;
}
(*HC)=(HuffmanCode)malloc((n+1)*sizeof(char*));//n个字符,有一个位置不用
cd=(char*)malloc(n*sizeof(char));
cd[n-1]='\0';
for(i=1;i<=n;i++)
{
start=n-1;
for(c=i,f=(*HT)[i].parent;f!=0;c=f,f=(*HT)[f].parent)
{
if((*HT)[f].lchild==c)
cd[--start]='0';
else
cd[--start]='1';
}
(*HC)[i]=(char*)malloc((n-start)*sizeof(char));
strcpy(&(*(*HC)[i]),&cd[start]);
}
free(cd);
}
void main()
{
HuffmanTree HT;
HuffmanCode HC;
int i;
int a[8]={12,5,7,8,33,10,2,6};
HuffmanCoding(&HT,&HC,a,8);
for(i=1;i<=15;i++)
printf("%d %d %d %d\n",HT[i].weight,HT[i].parent,HT[i].lchild,HT[i].rchild);
//printf("\n");
for(i=1;i<=8;i++)
printf("%s\n",*(HC[i]));//该如何输出每个字符的哈夫曼编码啊?
}