求助 运行时不显示该输出的编码和译码
程序代码:
#include<stdio.h> #include<stdlib.h> #include<conio.h> #define MAXVALUE 10000 #define MAXLEAF 30 #define MAXNODE MAXLEAF*2-1 #define MAXBIT 50 typedef struct node{ char letter; int weight; int parent; int lchild; int rchild; }HNodeType; typedef struct { char letter; int bit[MAXBIT]; int start; }HCodeType; typedef struct { char s; int num; }Bowen; /*哈夫曼树的构造算法*/ void HuffmanTree(HNodeType HuffNode[],int n,Bowen a[]) { int i,j,m1,m2,x1,x2,temp1;char temp2; for(i=0;i<2*n-1;i++) { HuffNode[i].letter=NULL; HuffNode[i].weight=0; HuffNode[i].parent=-1; HuffNode[i].lchild=-1; HuffNode[i].rchild=-1; } for(i=0;i<n-1;i++) for(j=i+1;j<n-1;j++) if(a[j].num>a[i].num) { temp1=a[i].num;a[i].num=a[j].num;a[j].num=temp1; temp2=a[i].s;a[i].s=a[j].s;a[j].s=temp2;} for(i=0;i<n;i++) { HuffNode[i].weight=a[i].num; HuffNode[i].letter=a[i].s;} for(i=0;i<n-1;i++) /*构造哈夫曼树*/ { m1=m2=MAXVALUE; x1=x2=0; for(j=0;j<n+i;j++) /*找出的两棵权值最小的子树*/ { if(HuffNode[j].parent==-1&&HuffNode[j].weight<m1) { m2=m1;x2=x1; m1=HuffNode[j].weight; x1=j; } else if(HuffNode[j].parent==-1&&HuffNode[j].weight<m2) { m2=HuffNode[j].weight; x2=j; } } /*将找出的两棵子树合并为一棵子树*/ HuffNode[x1].parent=n+i;HuffNode[x2].parent=n+i; HuffNode[n+i].weight=HuffNode[x1].weight+HuffNode[x2].weight; HuffNode[n+i].lchild=x1; HuffNode[n+i].rchild=x2; } } /*生成哈夫曼编码*/ void HuffmanCode(int n,Bowen a[]) { HNodeType HuffNode[MAXNODE]; HCodeType HuffCode[MAXLEAF],cd; int i,j,c,p; char code[10]={'q','w','e','r','t','q','w','y','u','o'},*m; HuffmanTree(HuffNode,n,a); /*建立哈夫曼树*/ for(i=0;i<n;i++) /*求每个叶子结点的哈夫曼编码*/ { cd.start=n-1; c=i; p=HuffNode[c].parent; while(p!=-1) /*由叶结点向上直到树根*/ { if(HuffNode[p].lchild==c) cd.bit[cd.start]=0; else cd.bit[cd.start]=1; cd.start--; c=p; p=HuffNode[c].parent;} for(j=cd.start+1;j<n;j++) /*保存求出的每个叶结点的哈夫曼编码和编码的起始位*/ HuffCode[i].bit[j]=cd.bit[j]; HuffCode[i].start=cd.start; } printf("输入的哈夫曼编码是:\n"); for(i=0;i<10;i++) {code[i]=NULL; printf("%s",code[10]); m=code; c=2*n-2;} printf("\n"); printf("输出哈夫曼译码:\n"); while(*m!=NULL) { if(*m=='0') { c=i=HuffNode[c].lchild; if(HuffNode[c].lchild==-1&&HuffNode[c].rchild==-1) { printf("%c",HuffNode[i].letter); c=2*n-2; } } if(*m=='1') { c=i=HuffNode[c].rchild; if(HuffNode[c].lchild==-1&&HuffNode[c].rchild==-1) { printf("%c",HuffNode[i].letter);c=2*n-2; } } m++; } printf("\n"); } int main(void) { Bowen data[30]; char c[10]={'q','w','e','r','t','q','w','y','u','o'},*p; int i,j,count=0; printf("\n 输入的一些字符是:"); for(j=0;j<10;j++) { printf("%c",c[j]); } for(i=0;i<30;i++) { data[i].s=NULL; data[i].num=0;} p=c; while(*p) { for(i=0;i<=count+1;i++) { if(data[i].s==NULL) { data[i].s=*p;data[i].num++;count++;break; } else if(data[i].s==*p) { data[i].num++;break; } } p++; } printf("\n"); HuffmanCode(count,data); getch(); }
利用哈夫曼编码进行通信可以大大提高信道利用率,缩短信息传输时间,降低传输成本。根据哈夫曼编码的原理,根据用户输入的一段文本,请编程实现的哈夫曼编码的编码与解码过程,并给出该段文本的编码结果与解码结果。
注意:1.测试文本可以预先存储在文件中
2.叶结点的权重直接从文本中统计得出