资源描述:
《C语言实现哈夫曼编码.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、/*先根据位权构造一颗哈夫曼树,测试数据0.050.10.150.20.250.25,再从叶子结点到根结点编码。程序结果保存在out.dat中。*/#include#include#include#defineN6typedefstruct{doubleweight;intparent,lchild,rchild;}HuffmanTree;voidSelect(HuffmanTree*HT,inti,int*s1,int*s2){intn,T=0,T1;for(n=1;
2、n
3、fmanTree*p;if(n<=1)return;m=2*n-1;HT[0].weight=10000;w++;for(p=HT+1,i=1;i<=n;++i,++w,++p){p->weight=*w;p->lchild=0;p->rchild=0;p->parent=0;}for(;i<=m;++i,++p){p->weight=0;p->lchild=0;p->rchild=0;p->parent=0;}for(i=n+1;i<=m;++i){Select(HT,i,&s1,&s2);HT[s1].parent=i;H
4、T[s2].parent=i;HT[i].lchild=s1;HT[i].rchild=s2;HT[i].weight=HT[s1].weight+HT[s2].weight;}cd=malloc(n*sizeof(char));cd[n-1]=' ';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]='1';elsecd[--start]='0';HC[i]=(c
5、har*)malloc((n-start)*sizeof(char));strcpy(HC[i],&cd[start]);}free(cd);}voidmain(){HuffmanTree*HT;inti;char**HC;doublew[N+1];floattemp;FILE*fp1,*fp2;HT=malloc((N)*sizeof(HuffmanTree));HC=malloc((N+1)*sizeof(char*));if((fp1=fopen("in.dat","rb"))==NULL){printf("不能打开文件
6、!");exit(1);}if((fp2=fopen("out.dat","a"))==NULL){printf("不能打开文件!");exit(1);}for(i=1;i<=N;i++){fscanf(fp1,"%f",&temp);w[i]=temp;}fclose(fp1);HuffmanCoding(HT,HC,w,N);for(i=1;i<=N;i++){fprintf(fp2,"%f的Huffman编码为:%s",w[i],HC[i]);}fclose(fp2);printf("编码成功!");}/
7、*文件in.dat内容:0.050.10.150.20.250.25*/