c语言哈夫曼编码数据结构试验,[C语言][数据结构]哈夫曼树(Huffman)的构造与实现...

#include

#include

#include

#define n 6

#define m 2*n-1

typedef struct

{

float weight;

int lchild,rchild,parent;

}codenode;

typedef codenode huffmantree[m];

typedef struct

{

char ch;

char bits[n+1];

}code;

typedef code huffmancode[n];

//哈夫曼树的初始化

void inithf(huffmantree T)

{

int i;

for (i=0;i

{

T[i].weight=0;

T[i].parent=-1;

T[i].lchild=-1;

T[i].rchild=-1;

}

}

//输入哈夫曼的数据

void inputhf(huffmantree T)

{

int i;

float k;

for (i=0;i

{

scanf("%f",&k);

T[i].weight=k;

}

}

void selectmin(huffmantree T,int k,int *p1,int *p2)

{

int i;

float small1=10000,small2=10000;

for(i=0;i

{

if (T[i].parent==-1)

if(T[i].weight

{

small2=small1;

small1=T[i].weight;

*p2=*p2;

*p1=i;

}

else

if (T[i].weight

{

small2=T[i].weight;

*p2=i;

}

}

}

//建立哈夫曼树

void creathftree(huffmantree T)

{

int i,p1,p2;

inithf(T);

inputhf(T);

for(i=n;i

{

selectmin(T,i-1,&p1,&p2);

T[p1].parent=T[p2].parent=i;

T[i].lchild=p1;

T[i].rchild=p2;

T[i].weight=T[p1].weight+T[p2].weight;

}

}

//哈夫曼编码表

void creathfcode(huffmantree T,huffmancode H)

{

int c,p,i,start;

char cd[n+1];

cd[n]='\0';

for(i=0;i

{

H[i].ch=getchar();

start=n;

c=i;

while((p=T[c].parent)>=0)

{

cd[--start]=(T[p].lchild==c)?'0':'1';

c=p;

}

strcpy(H[i].bits,&cd[start]);

}

}

//编码

void zip(huffmancode H,char *ch,char *s)

{

int j=0;

char *p[n];

unsigned int i;

for (i=0;i

{

while (ch[i]!=H[j].ch) j++;

p[i]=H[j].bits;

}

strcpy(s,p[0]);

for (i=1;i

strcat(s,p[i]);

puts(s);

}

//解码

void uzip(huffmancode H,char *s,huffmantree T)

{

int j=0,p;

unsigned int i;

char ch[n+1];

while (i

{

p=m-1;

while (T[p].lchild!=-1)

{

if(s[i]=='0')

{

p=T[p].lchild;

i++;

}

else

{

p=T[p].rchild;

i++;

}

}

ch[j]=H[p].ch;

j++;

}

ch[j]='\0';

puts(ch);

}

void main()

{

char ch[]="abcdef",s[36];

huffmantree T;

huffmancode H;

creathftree(T);

getchar();

creathfcode(T,H);

zip(H,ch,s);

uzip(H,s,T);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值