课程设计报告:Huffman编码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
课程设计报告:Huffman编码
题目:从键盘接收任意一字符串,以‘#’结尾,字符串中某字符出现的次数作为该字符的权值,利用得到的权值构建huffman树、从而求得字符对应的huffman
一、需求分析
1. 从键盘接收任意一字符串,以‘#’结尾,字符串中某字符出现的次数作为该字符的权值,利用得到的权值构建huffman树、从而求得字符对应的huffman编码。
注意:我们要求在实现select函数时,把权值最小的作为左孩子,权值次小的作为右孩子。
输入的形式和输入值的范围
用键盘输入,输入任意一字符串,以‘#’结尾。如:abcbcc# 输出的形式:
输出字符、其对应权值、以及huffman编码。
输出格式:字符---权值---编码
如:a---1---10
b---2---11
c---3---0
二、概要设计
Huffman树的定义:
typedef struct
{
unsigned int weight; //权
unsigned int parent,lchild,rchild; //父母、左孩子、右孩子
}htnode,*huffmantree;
Huffman编码的定义:
typedef char **huffmancode;
字符串的定义:
typedef struct node
{
char zifu;
unsigned int b;
}*node1,node2;
函数的调用:
void select(huffmantree HT,int a,int &s1,int &s2)
//创建huffman函数
oid huffmancoding(huffmantree &HT,huffmancode &HC,int *w,int n) //调用huffman函数,构造huffman编码
void shuru(node1 shuzu[100],int &n) //输入一串字符,进行处理,统计每个字符出现的次数
三、详细设计
主函数:
int main()
{
int n=0,*w;
huffmantree HT;
huffmancode HC;
node1 shuzu[100];
shuru(shuzu,n);
w=new int[n];
for(int j=0;j w[j]=shuzu[j+1]->b; huffmancoding(HT,HC,w,n); for(int i=1;i<=n;i++) cout< return 0; } 构造huffman树 void select(huffmantree HT,int a,int &s1,int &s2) { int min,num[2],m=0; num[0]=-1; for(int j=0;j<2;j++,m=0) for(int i=1;i<=a-1;i++) {if(HT[i].parent==0 && num[0]!=i) { if(m==0) { min=HT[i].weight; num[j]=i; } m++; if(HT[i].weight {num[j]=i;min=HT[i].weight;} } } s1=num[0],s2=num[1]; } 构造huffman编码 void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n){ //w存放n个字符的权值,构造赫夫曼树HT,并求出n个字符的赫夫曼树编码HC。 if(n<=1) return; m=2*n-1; HT=(HuffmanTree)malloc((m+1)*sixeof(HTNode)) //0号单元未用 for(p=HT,i=1;i<=n;++i,++p,++w) *p={*w,0,0,0}; for(;i<=m;++i,++p) *p={0,0,0,0} for(i=n+1;i<=m;+++i){ //建立赫夫曼树 //在HT[1...i-1]选择parent为0且weight最小的两个结点,其序号分别为s1和s2 Select(HT,i-1,s1,s2) HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2; HT[i].weight=HT[s1].weight+HT[s2].weight; } HC=(HuffmanCode)malloc((n+1)*sizeof(char*)); cd=(char *)malloc(n*sizeof(char)); cd[n-1]="\0"; 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]="0"; else cd[--start]="1"; HT[i]=(char *)malloc((n-start)*sizeof(char)); strcpy(HC[i],&cd[start]); } free(cd); } 五、测试数据与测试结果 第一组: ababccba# a---3---11 b---3---0 c---2---10 Press any key to continue 第二组: abdhjsabzmxusadbxvxn# a---3---100 b---3---101 d---2---1111 h---1---0010 j---1---0011 s---2---000 z---1---0100 m---1---0101