1、 char ch; int weight; int parent; int LChild; int RChild;HTNode,HuffmanTreeMAXSIZE;typedef struct /定义结构体 int number;NUMMAXSIZE;typedef char * HuffmanCodeN+1;void menu(void);void getchars(char *str,int *len); /输入字符串void Init(int AMAXSIZE,int *n); /输入结点的权值(备用)void CrtHuffmanTree(HuffmanTree ht,NUM w,i
2、nt n);/创建哈夫曼树void select(HuffmanTree ht,int pos,int *s1,int *s2);void CrtHuffmanCode(HuffmanTree ht,HuffmanCode hc,int n);/创建哈夫曼编码void showHuffmanCode(HuffmanCode hc,int n,NUM w,char *str,char *code,int len);/显示哈夫曼编码及各结点详细信息void total(char strMAXSIZE,NUM w,int *n,int len);void CrtHuffmanDecode(Huffm
3、anTree ht,char *code,int n);/进行译码工作void CrtHuffmanDecode(HuffmanTree ht,char *code,int n) char resultMAXSIZE=0; int rootIndex=n*2-1; int i,j,root=rootIndex; printf(n传过来的信息是:n); puts(&code1); for(i=j=1;i=(int)strlen(&code1)+1;i+) if(htroot.RChild=0) resultj+=htroot.ch; root=rootIndex; if(codei=1) roo
4、t=htroot.RChild; else root=htroot.LChild; resultj=0; printf(n译码的结果是:n%snn,&result1); puts(&void total(char strMAXSIZE,NUM w,int *n,int len) int i,j=1,k=1; for(i=1;=len; wi.number=0; wk.ch=strj; wk.number+; k+; for(j=2;jlen;j+) for(i=1;k; if(strj=wi.ch) wi.number+; break; if(i=k) wk.ch=strj; wk.numbe
5、r+; k+; *n=k-1;void showHuffmanCode(HuffmanCode hc,int n,NUM w,char *str,char *code,int len) int i,j;字符t权值t编码n=n;%ct%dt%sn,wi.ch,wi.number,hci);n字符编码是: for(j=1; if(stri=wj.ch) / printf(%s,hcj); strcat(&code1,hcj); / break; puts(&void CrtHuffmanCode(HuffmanTree ht,HuffmanCode hc,int n) int i,c,start,
6、p; char *cd; cd=(char *)malloc(n+1)*sizeof(char); cdn-1=0; start=n-1; c=i; p=hti.parent; while(p!=0) -start; if(htp.LChild=c) cdstart=0 else c=p; p=htp.parent; hci=(char *)malloc(n-start)*sizeof(char); strcpy(hci,&cdstart); free(cd);void select(HuffmanTree ht,int pos,int *s1,int *s2) int i,m1,m2;=po
7、s; if(hti.parent=0) m1=i; break; if(hti.weight=htm1.weight & hti.parent=0) m1=i; *s1=m1; m2=m1; for(i=1; if(hti.parent=0 & i!=m2) m1=i; break; for(i=1; if(hti.weight hti.parent=0 & m1=i; *s2=m1;void CrtHuffmanTree(HuffmanTree ht,NUM w,int n) /构造哈夫曼树htM+1,w存放n个权值 int i,m,s1,s2; hti.ch=wi.ch; hti.weig
8、ht=wi.number; hti.parent=0; hti.LChild=0; hti.RChild=0; m=2*n-1; for(i=n+1;=m; hti.ch= hti.weight=0; select(ht,i-1,&s1,&s2); hti.weight=hts1.weight+hts2.weight; hts1.parent=i; hts2.parent=i; hti.LChild=s1; hti.RChild=s2;void getchars(char *str,int *len)请输入一行字符串: gets(&str1); *len=strlen(str);/*void
9、Init(int wMAXSIZE,int *n) int num,i=1;请输入一组权值(以0结束): scanf(%dnum); while(num) wi=num; i+; scanf( *n=i-1;*/void main(void) HuffmanTree ht; HuffmanCode hc; char codeMAXSIZE= NUM w; int n,len; char strMAXSIZE; getchars(str,&len); total(str,w,&n,len);/ Init(w,&n); CrtHuffmanTree(ht,w,n); CrtHuffmanCode(ht,hc,n); showHuffmanCode(hc,n,w,str,code,len); CrtHuffmanDecode(ht,code,n);5.测试程序:输入一段英文 I am sunyu,i am a student.显示结果如下:运行成功!
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1