资源简介
用C语言,哈夫曼树的应用和实现,建立,编码,译码,另外界面也很美观,可直接运行
代码片段和文件信息
#include
#include
#include
#include
#include
#define n 6
#define m 2*n-1
typedef char datatype;
typedef struct
{
float weight;
datatype data;
int lchildrchildparent;
}hufmtree;
hufmtree tree[m];
typedef struct
{
char bits[n];
int start;
datatype data;
}codetype;
codetype code[n];
void showMenu();
void doChoice(char);
void doQuit();
void doListAll();
HUFFMAN(hufmtree tree[m]);
HUFFMANCODE(codetype code[n]hufmtree tree[m]);
HUFFMANDECODE(codetype code[n]hufmtree tree[m]);
HUFFMAN(hufmtree tree[]) /*建立哈夫曼树*/
{
int ijp1p2k;
char ch;
float small1small2f;
for(i=0;i {
tree[i].parent=0;
tree[i].lchild=0;
tree[i].rchild=0;
tree[i].weight=0.0;
tree[i].data=‘0‘;
}
for(i=0;i {
k=i+1;
printf(“请输入第%d个结点的结点值:“k);
fflush(stdin);
scanf(“%c“&ch);
tree[i].data=ch;
printf(“请输入第%d个结点的权值:“k);
scanf(“%f“&f);
tree[i].weight=f;
}
for( i=n;i {
p1=p2=0;
small1=small2=FLT_MAX; /* FLT_MAX是float类型的最大值*/
for(j=0;j<=i-1;j++)
if(tree[j].parent==0)
if((fabs(tree[j].weight-small1)>0.00001)&&(tree[j].weight {
small2=small1; /*改变最小权、次小权的对应位置*/
small1=tree[j].weight;
p2=p1;
p1=j;
}
else if((fabs(tree[j].weight-small2)>0.00001)&&(tree[j].weight /*改变次小权及位置*/
{
small2=tree[j].weight;
p2=j;
}
tree[p1].parent=i; /*结合并的两个结点的双亲域赋值*/
tree[p2].parent=i;
tree[i].lchild=p1;
tree[i].rchild=p2;
tree[i].weight=tree[p1].weight+tree[p2].weight;
}
}
void doListAll() /*列出哈夫曼树的结果状态*/
{
int i;
printf(“哈夫曼树的结果状态如下:\n“ );
printf(“======================================================================\n“);
printf(“数组下标 lchild data weight rchild parent\n“);
for (i = 0; i < m; i++)
{
printf(“%6d%6d %c %.2f%6d%6d\n“itree[i].lchildtree[i].datatree[i].weighttree[i].rchildtree[i].parent);
}
printf(“======================================================================\n“);
}
HUFFMANCODE(codetype code[]hufmtree tree[]) /*哈夫曼树编码*/
/*code 存放求出的哈夫曼编码的数组,tree 已知的哈夫曼树*/
{
int icpj;
codetype cd; /*缓冲变量*/
prin
- 上一篇:C++文件加密系统
- 下一篇:C++ 课程设计 扫雷系统 报告+源代码
评论
共有 条评论