资源预览内容
第1页 / 共3页
第2页 / 共3页
第3页 / 共3页
亲,该文档总共3页全部预览完了,如果喜欢就下载吧!
资源描述
可编辑#include#include#includeintm,s1,s2;typedefstructunsignedintweight;unsignedintparent,lchild,rchild;HTNode,*HuffmanTree;/动态分配数组存储哈夫曼树typedefchar*HuffmanCode;/动态分配数组存储哈夫曼编码表voidSelect(HuffmanTreeHT,intn)inti,j;for(i=1;i=n;i+)if(!HTi.parent)s1=i;break;for(j=i+1;j=n;j+)if(!HTj.parent)s2=j;break;for(i=1;iHTi.weight)&(!HTi.parent)&(s2!=i)s1=i;for(j=1;jHTj.weight)&(!HTj.parent)&(s1!=j)s2=j;voidHuffmanCoding(HuffmanTree&HT,HuffmanCodeHC,int*w,intn)/算法6.13/w存放n个字符的权值(均0),构造哈夫曼树HT,/并求出n个字符的哈夫曼编码HCinti,j;char*cd;intp;intcdlen;if(n=1)return;m=2*n-1;HT=(HuffmanTree)malloc(m+1)*sizeof(HTNode);/0号单元未用for(i=1;i=n;i+)/初始化HTi.weight=wi-1;HTi.parent=0;HTi.lchild=0;HTi.rchild=0;for(i=n+1;i=m;i+)/初始化HTi.weight=0;HTi.parent=0;HTi.lchild=0;HTi.rchild=0;puts(n哈夫曼树的构造过程如下所示:);printf(HT初态:n结点weightparentlchildrchild);for(i=1;i=m;i+)printf(n%4d%8d%8d%8d%8d,i,HTi.weight,HTi.parent,HTi.lchild,HTi.rchild);printf(按任意键,继续.);getchar();for(i=n+1;i=m;i+)/建哈夫曼树/在HT1.i-1中选择parent为0且weight最小的两个结点,/其序号分别为s1和s2。Select(HT,i-1);HTs1.parent=i;HTs2.parent=i;HTi.lchild=s1;HTi.rchild=s2;HTi.weight=HTs1.weight+HTs2.weight;printf(nselect:s1=%ds2=%dn,s1,s2);printf(结点weightparentlchildrchild);for(j=1;j=i;j+)printf(n%4d%8d%8d%8d%8d,j,HTj.weight,HTj.parent,HTj.lchild,HTj.rchild);printf(按任意键,继续.);getchar();/-无栈非递归遍历哈夫曼树,求哈夫曼编码cd=(char*)malloc(n*sizeof(char);/分配求编码的工作空间p=m;cdlen=0;for(i=1;i=m;+i)/遍历哈夫曼树时用作结点状态标志HTi.weight=0;while(p)if(HTp.weight=0)/向左HTp.weight=1;if(HTp.lchild!=0)p=HTp.lchild;cdcdlen+=0;elseif(HTp.rchild=0)/登记叶子结点的字符的编码HCp=(char*)malloc(cdlen+1)*sizeof(char);cdcdlen=0;strcpy(HCp,cd);/复制编码(串)elseif(HTp.weight=1)/向右HTp.weight=2;if(HTp.rchild!=0)p=HTp.rchild;cdcdlen+=1;else/HTp.weight=2,退回退到父结点,编码长度减1HTp.weight=0;p=HTp.parent;-cdlen;/HuffmanCodingintmain()HuffmanTreeHT;HuffmanCode*HC;int*w,n,i;puts(输入结点数:);scanf(%d,&n);getchar();HC=(HuffmanCode*)malloc(n*sizeof(HuffmanCode);w=(int*)malloc(n*sizeof(int);printf(输入%d个结点的权值n,n);for(i=0;in;i+)scanf(%d,&wi);getchar();HuffmanCoding(HT,HC,w,n);puts(n各结点的哈夫曼编码:);for(i=1;i=n;i+)printf(%2d(%4d):%sn,i,wi-1,HCi);getchar();精品文档
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号