资源描述:
《huffman编码c实现》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#includestdio.h>#includestdlib.h>#includestring.h>#includemalloc.h>#defineN20#defineM2*N-1#defineMin1000/*最小值*/typedefstruct{ charch;/*权值对应的字符*/ intweight;/*权值*/ intparent;/*双亲位置*/ intLchild;/*左孩子位置*/ intRchild;/*右孩子位置*/}HTNode,Huffmantree[M+1];charhc[N+1][N
2、+1];voidOutputHuffmancode(Huffmantreeht,intn);voidCrtHuffmancode(Huffmantreeht,intn);voidOutputHuffmantree(Huffmantreeht,intn);voidselect(Huffmantreeht,inta,int*s1,int*s2){ inti; intc1=Min; intc2; for(i=1;i=a;i++) { if(ht.parent==0&&ht.weightc1) { *s1
3、=i; c1=ht.weight; } } c2=Min; for(i=1;i=a;i++) { if(ht.parent==0&&(*s1!=i)&&c2>ht.weight) { *s2=i; c2=ht.weight; } }}voidCrtHuffmantree(Huffmantreeht,intw[],charelem[],intn){ inti; intm; ints1,s2; m=2*n-1; ht=(HTNode*)malloc((m)*siz
4、eof(HTNode)); for(i=1;i=n;i++) { ht.ch=elem[i-1]; ht.weight=w[i-1]; ht.parent=0; ht.Lchild=0; ht.Rchild=0; } for(i=n+1;i=m;i++) { ht.ch=' '; ht.weight=0; ht.parent=0; ht.Lchild=0; ht.Rchild=0; } /*初始化完毕*/ for(i=n+1;i=m;i++) { select(ht,i-1,
5、&s1,&s2);/*返回最小值和次小值的位置*/ ht.weight=ht[s1].weight+ht[s2].weight; ht[s1].parent=i; ht[s2].parent=i; ht.Lchild=s1; ht.Rchild=s2;/*建立树完毕*/ } OutputHuffmantree(ht,m); printf("nowbegincrthuffmancode"); CrtHuffmancode(ht,n); printf("crthuffmancodeend");
6、OutputHuffmancode(ht,n);}voidOutputHuffmantree(Huffmantreeht,intn){ inti; printf("number---weight---parent---Lchild---Rchild---huffmanchar"); for(i=1;i=n;i++) printf("%dt%dt%dt%dt%dt%c",i,ht.weight,ht.parent,ht.Lchild,ht.Rchild,ht.ch);}voidCrtH
7、uffmancode(Huffmantreeht,intn)/*建立编码*/{ inti,c,p; intstart; char*cd; cd=(char*)malloc((n+1)*sizeof(char)); memset(cd,' ',sizeof(cd)); for(i=1;i=n;i++) { start=n; cd[start]=' '; c=i; p=ht.parent; while(p!=0
8、) { start--; if(ht[p].Lchild==c) cd[start]='0'; else cd[start]='1'; c=p; p=ht[p].parent; }