您的位置:首页 > 编程语言 > C语言/C++

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

2015-05-13 20:39 405 查看
     

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

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

    下面是今天编写的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
;

//哈夫曼树的初始化
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
4000
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
='\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
;
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

    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: