哈夫曼树的编码和译码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include"stdafx.h"
#include"stdio.h"
#include"conio.h"
#include
#include
#include
using namespace std;
#define maxbit 100
#define Maxvalue 2000//最大权值整数常量#define Maxleaf 100//最大叶子结点数
#define size 300//0、串数组的长度
static int n;//实际的叶子结点数
struct HNodeType
{
int weight;
int parent;
int lchild;
int rchild;
int ceng;//结点相应的层数
char ch;//各结点对应的字符
};
struct HCodeType
{
int bit[maxbit];//存放编码的数组
int start;//编码在数组中的开始位置};
static HNodeType *HuffNode;//定义静态指针HNodeType *init()//初始化静态链表
{
HuffNode=new HNodeType[2*n-1];
for(int i=0;i<2*n-1;i++)
{
HuffNode[i].weight=0;
HuffNode[i].parent=-1;
HuffNode[i].lchild=-1;
HuffNode[i].rchild=-1;
HuffNode[i].ceng=-1;
HuffNode[i].ch='0';
}
return HuffNode;
}
void HaffmanTree()//建立哈夫曼树
{
int i,j;
int m1,m2,x1,x2;
cout<<"请输入叶子结点对应的权值"< for(i=0;i { cin>>HuffNode[i].weight; } flushall();//清除缓存 cout<<"请输入叶子结点对应的字符"< for(i=0;i { cin.get(HuffNode[i].ch); } for(i=0;i { m1=m2=Maxvalue; x1=x2=0; for(j=0;j { if(HuffNode[j].parent==-1&&HuffNode[j].weight { m2=m1; x2=x1; m1=HuffNode[j].weight; x1=j; } else if(HuffNode[j].parent==-1&&HuffNode[j].weight { 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; HuffNode[x1].ceng=n-i; HuffNode[x2].ceng=n-i; HuffNode[n+i].ceng=n-i-1; } ofstream outfile("hfmtree.dat",ios::out|ios::binary);//建立文件存入哈夫曼树if(!outfile) cerr<<"open file error!"< for(i=0;i<2*n-1;i++) outfile.write((char*)(&HuffNode[i]),sizeof(HuffNode[i])); outfile.close(); } void HaffmanCode()//哈夫曼编码 { int i,j,k,m,c,p,flag=0; HCodeType HuffCode[Maxleaf],cd; ifstream infile("hfmtree.dat",ios::in|ios::binary);//打开文件读取数据 if(!infile) cerr<<"open file error!"< for( i=0;i<2*n-1;i++) { infile.read((char*)(&HuffNode[i]),sizeof(HuffNode[i])); } infile.close(); for(i=0;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 HuffCode[i].bit[j]=cd.bit[j]; HuffCode[i].start=cd.start; } cout<<"叶子结点所对应的字符及编码(形如:A--100):"< for(i=0;i { cout< for(j=HuffCode[i].start+1;j