哈夫曼编码和译码c语言,C语言实现哈夫曼编码与译码.doc

信息工程1102 苑博 2011116020230

C语言实现哈夫曼编码与译码

#include;

#define n 6 ;

#define m (2*n-1) ;

#define maxval 10000.0;

#define maxsize 100 ;

typedef struct;

{

char ch;

float weight;

int lchild,rchild,parent;

}hufmtree;

typedef struct;

{

char bits[n];

int start;

char ch;

}codetype;

void huffman(hufmtree tree[]);

void huffmancode(codetype code[],hufmtree tree[]);

void decode(hufmtree tree[]);

void main()

{

printf(" ——哈夫曼编码——\n");

printf("总共有%d个字符\n",n);

hufmtree tree[m];

codetype code[n];

int i,j;

huffman(tree);

huffmancode(code,tree);

printf("【输出每个字符的哈夫曼编码】\n");

for(i=0;i

{

printf("%c: ",code[i].ch);

for(j=code[i].start;j

printf("%c ",code[i].bits[j]);

printf("\n");

}

printf("【读入电文,并进行译码】\n");

decode(tree);

}

void huffman(hufmtree tree[])

{

int i,j,p1,p2;

float small1,small2,f;

char c;

for(i=0;i

{

tree[i].parent=0;

tree[i].lchild=-1;

tree[i].rchild=-1;

tree[i].weight=0.0;

}

printf("【依次读入前%d个结点的字符及权值(中间用空格隔开)】\n",n);

for(i=0;i

{

printf("输入第%d个字符为和权值",i+1);

scanf("%c %f",&c,&f);

getchar();

tree[i].ch=c;

tree[i].weight=f;

}

for(i=n;i

{

p1=0;p2=0;

small1=maxval;small2=maxval; /

for(j=0;j

if(tree[j].parent==0)

if(tree[j].weight

{

small2=small1;

small1=tree[j].weight;

p2=p1;

p1=j;

}

else

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

}

}//huffman

void huffmancode(codetype code[],hufmtree tree[])

{

int i,c,p;

codetype cd; for(i=0;i

{

cd.start=n;

cd.ch=tree[i].ch;

c=i;

p=tree[i].parent;

while(p!=0)

{

cd.start--;

if(tree[p].lchild==c)

cd.bits[cd.start]='0';

else

cd.bits[cd.start]='1';

c=p;

p=tree[p].parent;

}

code[i]=cd;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值