第1个回答 2011-12-22
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct node
{
int weight;
char ch;
struct node *left,*right;
}NODE;
typedef struct hcode
{
char ch;
int len;
unsigned char code[256];
}hcode;
int comp(const void *a,const void*b)
{
return (*(NODE **)(b))->weight-(*(NODE **)(a))->weight;
}
hcode codes[256]={{0,0,{0}}};
NODE *tree;
NODE *newNode(int weight,char ch,NODE *left,NODE *right)
{
NODE *node;
node=(NODE *)malloc(sizeof(NODE));
node->weight=weight;
node->ch=ch;
node->left=left;
node->right=right;
return node;
}
void count(char *str)
{
char *p=str;
NODE *node,*tmp1,*tmp2;
NODE *nodes[512];
int ch[256]={0};
int c=0,i;
while (*p>0)
{
ch[(int)*p]++;
p++;
}
for(i=0;i<256;i++)
if(ch[i]>0)
{
nodes[c]=newNode(ch[i],i,NULL,NULL);
c++;
printf("%c的权值为:%d\n",(char)i,ch[i]);
}
nodes[c]=newNode(0,0,NULL,NULL);
while (c>0)
{
qsort(nodes,c+1,sizeof(NODE *),comp);
tmp1=nodes[c];
tmp2=nodes[c-1];
node=newNode(tmp1->weight+tmp2->weight,0,tmp1,tmp2);
nodes[c-1]=node;
c--;
}
tree=nodes[0];
}
void convert(NODE *node,int len)
{
static unsigned code[256]={0};
int i;
if(node->left==NULL&&node->right==NULL)
{
for(i=0;i<=len;i++) codes[(int)node->ch].code[i]=code[i] ;
codes[(int)node->ch].len=len;
codes[(int)node->ch].ch=node->ch;
}
if(node->left!=NULL)
{
code[len]=0;
convert(node->left,len+1);
}
if (node->right!=NULL)
{
code[len]=1;
convert(node->right,len+1);
}
return ;
}
void encode(char *src,char *dst)
{
char *ps=src,*pd=dst;
int pb=0,i;
while(*ps>'\0') ps++;
ps=(src-1);
printf("编码后的二进制表示为:\n");
do
{
ps++;
for(i=0;i<codes[(int)*ps].len;i++)
{
printf("%d",codes[(int)*ps].code[i]);
*pd=((*pd)<<1)+codes[(int)*ps].code[i];
pb++;
if(pb>=8){pd++;pb=0;}
}
}while(*ps>'\0');
*pd=*pd<<(8-pb);
*(pd+1)='\0';
}
void decode(char *src,char *dst)
{
char *ps=src,*pd=dst;
int pb=7,ts;
NODE *node=tree;
while (1)
{
if(node->left==NULL&&node->right==NULL)
{
*pd=node->ch;
//printf("%c",node->ch);
if (*pd==0) return ;
pd++;
node=tree;
}
else
{
ts=(*ps)>>pb&0x1;
pb--;
if(pb<0) {pb=7;ps++;}
if (ts==0)
{
node=node->left;
}
else
{
node=node->right;
}
}
}
printf("\n");
}
int main()
{
int i,j;
//char str[1024]="qwertyuiopasdfghjklzxcvbnm1234567890\0";
char str[1024]={0};
char out[1024]={0};
char out2[1024]={0};
printf("请输入要测试的字符串:\n");
gets(str);
printf("输入的字符串为:%s\n长度为:%d\n",str,strlen(str));
count(str);
convert(tree,0);
for(i=0;i<256;i++)
{
if(codes[i].len>0)
{
printf("%c的Huffman编码为:",(char)i);
for(j=0;j<codes[i].len;j++)
printf("%d ",codes[i].code[j]);
printf("\n");
}
}
encode(str,out);
printf("\n编码后的字符串为:%s\n长度为:%d\n",out,strlen(out));
decode(out,out2);
printf("\n解码后的字符串为:%s\n长度为:%d\n",out2,strlen(out2));
return 0;
}