[C语言]哈夫曼树(Huffman)的构造与实现

本文详细介绍了使用C语言实现哈夫曼树编码与解码的过程,包括初始化、输入数据、建立哈夫曼树、生成编码表、编码与解码操作。通过实践加深对哈夫曼编码应用的理解。

     

     C语言数据结构中哈夫曼树是个重要的内容。哈夫曼主要是它的编码应用可以保证译码的非二义性。

    每天坚持编写一个程序,持之以恒,我们就会更加熟练的进行编程,从而为以后打下基础。

    下面是今天编写的HUffman树的源代码,因为纯手写,没有运行,了解了原理才是最重要的嘛!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#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<m;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<n;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<k;i++)
{
if (T[i].parent==-1)
if(T[i].weight<small1)
{
small2=small1;
small1=T[i].weight;
*p2=*p2;
*p1=i;
}
else
if (T[i].weight<small2)
{
small2=T[i].weight;
*p2=i;
}
}
}


//建立哈夫曼树
void creathftree(huffmantree T)
{
int i,p1,p2;
inithf(T);
inputhf(T);
for(i=n;i<m;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<n;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<strlen(ch);i++)
{
while (ch[i]!=H[j].ch) j++;
p[i]=H[j].bits;
}
strcpy(s,p[0]);
for (i=1;i<n;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<strlen(s))
{
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);
}
希望大家可以一起多交流,一起进步哦。

文章在我论坛的地址:http://www.jsjer.com/forum.php?mod=viewthread&tid=762

    


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值