typedef struct { int weight; int parent,lchild,rchild; }HTNode,* HuffmanTree;//哈夫曼结构 typedef char **HuffmanCode;//哈夫曼编码 HuffmanTree HT; HuffmanCode HC; int *w,i=0,j=0,n=0,number=0; char *z; void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n)//W存放N个字符的权值,构造哈夫曼树HT,并求出N个字符的哈夫曼编码HC { int m,i,s1,s2,start; int c,f; HuffmanTre e p; char *cd; if(n<=1) return; m=2*n-1; HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); for(p=HT+1,i=1;i<=n;++i,++p,++w)//初使化前n个结点,将权值放入每个结点中 { p->weight=*w; p->parent=0; p->lchild=0; p->rchild=0; } for(;i<=m;++i,++p)//初使化n+1到m个结点的parent值 p->parent=0; for(i=n+1;i<=m;++i)//建树 { j=1; p=HT; while((j<=i-1)&&(p[j].parent!=0))//未建结点个数 j++; s1=j; while(j<=i-1) { if(p[j].parent==0&&p[j].weights2) { j=s1; s1=s2; s2=j; } HT[s1].parent=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*)); 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)//左0右1编码 cd[--start]='0'; else cd[--start]='1'; HC[i]=(char*)malloc((n-start)*sizeof(char)); strcpy(HC[i],&cd[start]); //复制串 } free(cd); } void Initialization()//初使化,从终端读入字符集大小n,以及n个字符和n个权值,建树,并存入文件中 { int num; int quan; cout<<"请输入字符集个数:"; cin>>num; n=num; w=(int*)malloc(n*sizeof(int));//存放权 z=(char*)malloc(n*sizeof(char));//存放字符 cout<<"请依次输入"<>cs; *(z+i)=*cs; } cout<>quan; *(w+i)=quan; } cout<<"字母表为"; for(i=0;i<=n-1;i++) { cout<rchild,HT); cout<weight<weight); Print(HT+p->lchild,HT); number--; fclose(TreePrint); } } void main() { char a; while(a!='Q') { cout<<"请选择要执行的命令:"<>a; switch(a) { case'I': Initialization();//初使化,建立哈夫曼树 break; case'S': InputMessage();//输入要翻译的报文 break; case'E': Coding();//读取报文并编码 break; case'D': Decoding();//将代码进行译码 break; case'P': cout<<"打印编码"<