哈夫曼编码实验报告Word格式文档下载.docx
《哈夫曼编码实验报告Word格式文档下载.docx》由会员分享,可在线阅读,更多相关《哈夫曼编码实验报告Word格式文档下载.docx(10页珍藏版)》请在冰豆网上搜索。
voidselectmin(hfmtt,inti,int*p1,int*p2)选中两个权值最小的函数
voidcreathfmt(hfmtt)创建哈夫曼树的函数
voidphfmnode(hfmtt)对字符进行初始编码
voidhuffpath递归求哈夫曼编码
程序执行结果
第一次运行结果:
第二次运行结果:
第三次运行结果:
结论
本程序思路基本正确,运行结果合法的,可以满足哈夫曼编码的转存和翻译。
编程中遇到的问题以及解决方法
1.程序在运行中多次出现溢出,后发现是在生成哈夫曼树时没有将数组下标附初值。
2.递归过程死循环,后发现是没有设置边界条件。
附录
//aa.cpp:
Definestheentrypointfortheconsoleapplication.
//
#include"
stdafx.h"
#include<
stdio.h>
stdlib.h>
string.h>
#defineMAXLEN1000
typedefstruct
{
intweight;
intlchild;
intrchild;
intparent;
charkey;
}htnode;
typedefhtnodehuff[MAXLEN];
intn=0;
voidinithuff(hufft)//对结构体进行初始化
inti;
printf("
\n"
);
for(i=0;
i<
2*n-1;
i++)
{
t[i].lchild=-1;
t[i].rchild=-1;
t[i].parent=-1;
}
}
voidinputweight(hufft)//输入函数
intw;
//w表示权值
inti,len,str[1000];
chark[1000];
//k表示获取的字符
请输入测试文本:
gets(k);
len=strlen(k);
1000;
i++)str[i]=0;
len;
i++)str[k[i]]++;
if(str[i]!
=0)
{
t[n].key=i;
t[n].weight=str[i];
n++;
}
}
for(i=n;
MAXLEN;
i++)t[i].weight=0;
}
voidselectmin(hufft,inti,int*p1,int*p2)//选中两个权值最小的函数
longmin1=999999;
longmin2=999999;
intj;
for(j=0;
j<
=i;
j++)//选择最小权值字符的下标返回
if(t[j].parent==-1)
if(min1>
t[j].weight)
min1=t[j].weight;
*p1=j;
j++)//选择次小权值字符的下标还回
if(min2>
t[j].weight&
&
j!
=(*p1))//注意此处需j!
=(*p1))才能保证是次小的
min2=t[j].weight;
*p2=j;
voidcreathuff(hufft)//创建哈夫曼树的函数
inti,p1,p2;
inputweight(t);
inithuff(t);
selectmin(t,i-1,&
p1,&
p2);
t[p1].parent=i;
t[p2].parent=i;
t[i].lchild=p1;
t[i].rchild=p2;
t[i].weight=t[p1].weight+t[p2].weight;
voidprinthuff(hufft)//打印哈夫曼树
哈夫曼树结构:
\t\t权重\t父母\t左孩子\t右孩子\t字符\t"
\t\t%d\t%d\t%d\t%d\t%c"
t[i].weight,t[i].parent,t[i].lchild,t[i].rchild,t[i].key);
voidhuffpath(hufft,inti,intj)//编码的重要哈夫曼树路径递归算法
inta,b;
a=i;
b=j=t[i].parent;
if(t[j].parent!
=-1)
{
i=j;
huffpath(t,i,j);
if(t[b].lchild==a)
0"
else
1"
voidphfmnode(hufft)//对字符进行初始编码
{
inti,j,a;
哈夫曼编码"
n;
j=0;
\t\t%c\t"
t[i].key,t[i].weight);
voidbianma(hufft)//对用户输入的文章进行编码
charr[1000];
//用来存储输入的字符串
inti,j;
请输入需要编码的字符:
"
gets(r);
编码结果为:
r[j]!
='
\0'
;
j++)
if(r[j]==t[i].key)
voidyima(hufft)//对用户输入的密文进行译码
charr[100];
inti,j,len;
j=2*n-2;
//j初始从树的根节点开始
请输入需要译码的字符串:
len=strlen(r);
译码的结果是:
if(r[i]=='
0'
)
j=t[j].lchild;
if(t[j].lchild==-1)
%c"
t[j].key);
elseif(r[i]=='
1'
j=t[j].rchild;
if(t[j].rchild==-1)
\n\n"
intmain()
我的学号是:
07112039\n"
huffht;
charflag;
creathuff(ht);
printhuff(ht);
phfmnode(ht);
\n【1】编码\t【2】\t译码\t【0】退出"
\n您的选择:
flag=getchar();
getchar();
while(flag!
if(flag=='
)
bianma(ht);
elseif(flag=='
2'
yima(ht);
您的输入有误,请重新输入。
system("
pause"