|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
typedef struct tree
{
char c;
struct tree *left,*right;
} T,*TT;
typedef struct wet
{
TT tr;
int weight;
struct wet *next;
} W,*WW;
typedef struct
{
int size;
WW frist;
} HF,*HHF;
typedef struct r
{
TT root;
}R,*RR;
typedef struct table_tree
{
char c;
char num[MAX];
struct table_tree*next;
}TB;
HF head; R r;char num[MAX]; TB *tb=NULL;
//将生成的数据结构连成链表。
int add_tree(WW tree_wet,HF*x)
{
WW p=x->frist;
if(x->frist==NULL)
{
x->frist=tree_wet;
tree_wet->next=NULL;
x->size=1;return 0;
}
else
{
if(tree_wet->weight<=x->frist->weight)
{
tree_wet->next=x->frist;
x->frist=tree_wet;x->size++;return 0;
}
else
{
while(p->next!=NULL)
{
if(tree_wet->weight<=p->next->weight)
{
tree_wet->next=p->next;
p->next=tree_wet;x->size++;
return 0;
}
p=p->next;
}
if(p->next==NULL)
{
p->next=tree_wet;
tree_wet->next=NULL;x->size++;return 0;
}
}
}
}
//生成数据结构。
int create( char*weight)
{
TT tree_fp;
WW tree_wet;
for(int i=0; i<256; i++)
{
if(weight[i]!=0)
{
tree_fp=(TT)malloc(sizeof(T));
tree_wet=(WW)malloc(sizeof(W));
tree_fp->left=NULL;
tree_fp->right=NULL;
tree_fp->c=(char)i;
tree_wet->weight=weight[i];
tree_wet->tr=tree_fp;
add_tree( tree_wet,&head);
}
}
}
//计算各字符出现的次数。
int get_weight( char *file)
{
char*weight=(char*)malloc(sizeof(char)*256);
for(int j=0; j<256; j++)
{
weight[j]=0;
}
for(int i=0; file[i]!='\0'; i++)
{
weight[(unsigned char)file[i]]++;
}
create(weight);
}
//取出两个结构处理成一个结构返回。
WW get_tree(HF *x)
{
WW p=x->frist;
if(x->size>0)
{
p=x->frist;
x->frist=x->frist->next;
x->size--;
}
else
{printf("空表\n");}
return p;
}
//生成赫曼夫二叉树。
WW create_he_tree( HF*x)
{
WW fp1,fp2;TT p;
if( x->frist==NULL||x->size==0)
{
printf("该表无数据\n");return 0;
}
while(x->size!=1)
{ p=(TT)malloc(sizeof(T));
fp1=get_tree(x);
fp2=get_tree(x);
p->left=fp1->tr;
p->right=fp2->tr;
fp1->weight+=fp2->weight;
fp1->tr=p;
add_tree(fp1,x);
}
}
//取出二叉树的根结点的地址;
int get_root( HF*x,R* r)
{
r->root=x->frist->tr;
return 0;
}
//遍历二叉树。
int play_seek( TT r, int i,TB**tb)
{
if(r->left==NULL||r->right==NULL)
{
if(r->left==NULL&&r->right==NULL)
{ num[i]='\0'; TB*fp=NULL;
fp=(TB*)malloc(sizeof(TB));
strcpy(fp->num,num);
fp->c=r->c;
if(*tb==NULL)
{ *tb=fp;fp->next=NULL; }
else
{ fp->next=*tb;*tb=fp;}
return 1;
}
return 0;
}
else
{ num[i]='0';
play_seek(r->left,i+1,tb);
num[i]='1';
play_seek(r->right,i+1,tb);
}
}
//打印赫曼夫压缩码。
int print_HE( TB** tb)
{
while(*tb!=NULL)
{
printf("%c:",(*tb)->c);
printf("%s\n",(*tb)->num);
*tb=(*tb)->next;
}
}
int main()
{
char num[]="I love you Xiao Jia yu ";
get_weight(num);
create_he_tree( &head);
get_root( &head,&r);
play_seek(r.root, 0,&tb);
print_HE(&tb);
return 0;
}
|
|