哈夫曼编码源代码

合集下载
相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include

#define MAXBIT 10

#define MAXVALUE 10000

#define MAXLEAF 30

#define MAXNODE MAXLEAF*2-1

typedef struct {

int bit[MAXBIT];

int start;

}Hcodetype;

typedef struct {

int weight;

int parent;

int lchild;

int rchild;

}Hnodetype;

void huffmantree(Hnodetype huffnode[MAXNODE],int n)

{

int i,j,m1,m2,x1,x2;

for(i=0;i<2*n-1;i++)

{

huffnode[i].weight=0;

huffnode[i].parent=-1;

huffnode[i].lchild=-1;

huffnode[i].rchild=-1;

}

for(i=0;i

{

printf("请输入第%d 个叶子结点的权值:\n",i);

scanf("%d",&huffnode[i].weight);

}

for(i=0;i

{

m1=m2=MAXVALUE;

x1=x2=0;

for(j=0;j

{

if(huffnode[j].weight

{

m2=m1;x2=x1;m1=huffnode[j].weight;

x1=j;

}

else if(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;

}

}

void main()

{

Hnodetype huffnode[MAXNODE];

Hcodetype huffcode[MAXLEAF],cd;

int i,j,c,p,n;

printf("输入叶子节点个数n\n");

scanf("%d",&n);

huffmantree(huffnode,n);

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;

}

for(i=0;i

{

printf("第%d个叶子结点的哈夫曼编码是:",i);

for(j=huffcode[i].start+1;j

printf("%d",huffcode[i].bit[j]);

printf("\n");

}

}

相关文档
最新文档