数据结构实验赫夫曼编码Word文件下载.docx
- 文档编号:21594237
- 上传时间:2023-01-31
- 格式:DOCX
- 页数:9
- 大小:124.65KB
数据结构实验赫夫曼编码Word文件下载.docx
《数据结构实验赫夫曼编码Word文件下载.docx》由会员分享,可在线阅读,更多相关《数据结构实验赫夫曼编码Word文件下载.docx(9页珍藏版)》请在冰豆网上搜索。
classtree
{
floatweight;
//权值
intparent;
//双亲
intlch,rch;
//左,右孩子
}
treehftree[m+1];
//规定从第一个元素hftree[1]开始使用数组元素,故定义长
度为m+1而不为m
结构类型:
typedefstruct
chardata;
intweight;
intlchild;
intrchild;
}huffnode;
charcd[MAX];
intstart;
}huffcode;
主程序
intmain()
初始化:
输入字符代码以及权值。
编制哈夫曼码:
根据权值建立二叉树,输出相应的根节点到叶结点的路径,便是哈夫曼编码。
编码:
输入字符,输出哈夫曼码。
译码:
输入哈夫曼,输出字符代码。
退出:
结束进程,退出程序。
三、实验题目:
构造哈弗曼树的算法。
4、实验源代码:
#include<
iostream.h>
string.h>
stdio.h>
charword;
intweight;
intparent,lchild,rchild;
}htnode,*huffmantree;
voidselect(huffmantreeht,inta,int&
s1,int&
s2)
ht[0].weight=1000;
s1=0;
for(inti=1;
i<
=a;
i++)
{
if(ht[i].parent==0)
{
if(ht[i].weight<
ht[s1].weight)
{
s1=i;
}
}
}
ht[s1].parent=1;
s2=0;
for(i=1;
ht[s2].weight)
s2=i;
voidcreathuffmantree(huffmantree&
ht,intN)
intm=2*N-1;
ints1,s2;
for(inti=N+1;
=m;
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;
ht[i].word='
x'
;
typedefchar**huffmancode;
voidcreathuffmancode(huffmantreeht,huffmancode&
hc,intN)
hc=newchar*[N+1];
char*cd=newchar[N];
cd[N-1]='
\0'
intstart,c,f;
=N;
start=N-1;
c=i;
f=ht[i].parent;
while(f!
=0)
--start;
if(ht[f].lchild==c)
cd[start]='
0'
else
1'
c=f;
f=ht[f].parent;
hc[i]=newchar[N-start];
strcpy(hc[i],&
cd[start]);
deletecd;
voidbianma(huffmancodehc,huffmantreeht,char*a,intN)
inti=0,j;
cout<
<
"
该字母组的赫夫曼编码是:
while(a[i]!
='
)
for(j=1;
j<
j++)
if(ht[j].word==a[i])
break;
cout<
hc[j];
i++;
endl;
voidchangetozimu(huffmantreeht,charb[],intN)
inti=0,f=2*N-1;
该赫夫曼编码的含义是:
while(b[i]!
if(b[i]=='
f=ht[f].lchild;
if(ht[f].lchild!
i++;
ht[f].word;
f=2*N-1;
elseif(b[i]=='
f=ht[f].rchild;
if(ht[f].rchild!
else
cout<
出现错误输入"
break;
voidmain()
intN;
请输入字母的数字"
cin>
>
N;
huffmantreeht=newhtnode[2*N];
=2*N-1;
ht[i].parent=0;
ht[i].lchild=0;
ht[i].rchild=0;
请输入第"
个字母"
cin>
ht[i].word;
请输入该字母的权值"
ht[i].weight;
creathuffmantree(ht,N);
哈弗曼树:
ht[i].word<
"
ht[i].weight<
ht[i].parent<
ht[i].lchild<
ht[i].rchild<
huffmancodehc;
creathuffmancode(ht,hc,N);
哈弗曼编码:
hc[i]<
char*a=newchar[100];
输入少于100个的字母符号"
a;
bianma(hc,ht,a,N);
请输入一段少于100的赫夫曼编码"
charb[100];
b;
changetozimu(ht,b,N);
五、实验源代码运行结果截图:
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 数据结构 实验 赫夫曼 编码