📄 huffuman.cpp
字号:
// Huffuman.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "float.h"
#include "stdlib.h"
#include "string.h"
//两种结构体的定义
struct hufnode
{
long wei;//权值
struct hufnode *lch;//左节点指针
struct hufnode *rch;//右节点指针
struct hufnode *prt;//父节点指针
char ch;//该字符
char code[30];//该节点的Haffuman编码
};
struct Input//用于对输入数据统计的结构体
{
long total;
char ch;
//struct Input * Inext;
};
static void myselect(struct hufnode *p,int k,int *i,int *j);
struct hufnode *hufm (int n,int m,struct Input w[]);
int main(int argc, char* argv[])
{
long a[128];
struct hufnode * p=NULL,*q=NULL,*t=NULL,*bh=NULL;
int i,j=0,n=0,j1;
char c=' ';
for(i=0;i<128;i++)//数组初始化
{
a[i]=0;
}
printf("请任意输入字符,并以'.'结束:\n");
scanf("%c",&c);
while(c!='.')//以'.'输入为结束
{
a[c]++;
scanf("%c",&c);
}
for(i=0;i<128;i++)//统计有输入的字符个数
{
if(a[i]!=0) n++;
}
struct Input *w=(struct Input *)malloc(n*sizeof(struct Input));
for(i=0;i<128;i++)
{
if(a[i]!=0)
{
w[j].ch=i;
w[j].total=a[i];
j++;
}
}
bh=hufm(n,2*n-1,w);
t=(bh-2*n+2);
for(j=0;j<n;j++)//求Huffuman编码的反序
{
p=t+j;q=p;i=0;
while(q!=bh)
{
if(q->prt->lch==q) p->code[i++]='0';
else p->code[i++]='1';
q=q->prt;
}
p->code[i]='\0';
}
for(i=0;i<n;i++)//将Huffuman编码字符串反序排列得到真正的Huffuman编码
{
char chm[10];j=0;
strcpy(chm,(t+i)->code);
while( (t+i)->code[j++]!='\0') ;
for(j1=j-2;j1>=0;j1--)
{
(t+i)->code[j-2-j1]=chm[j1];
}
(t+i)->code[j-1]='\0';
}
printf("您输入的字母的Haffuman编码为:\n");
for(i=0;i<n;i++)
{
if((t+i)->ch==' ') printf("空格 %s\n",(t+i)->code);
else if((t+i)->ch==10) printf("回车 %s\n",(t+i)->code);
else printf("%c %s\n",(t+i)->ch,(t+i)->code);
}
return 0;
}
static void myselect(struct hufnode *p,int k,int *i,int *j)
{
int m,n=0;
while( (n<k)&&( (p+n)->prt!=NULL ) ) n=n+1;
m=(p+n)->wei;
*i=n;
while(n<k)
{
if( ( ((p+n)->wei)<m )&&( (p+n)->prt==NULL ) )
{
*i=n;m=(p+n)->wei;
}
n=n+1;
}
n=0;
while( (n<k)&&( (p+n)->prt!=NULL )|| (n==(*i)) ) n=n+1;
m=(p+n)->wei;*j=n;
while(n<k)
{
if( ( ((p+n)->wei)<m )&&( (p+n)->prt==NULL )&& ( n!=(*i)) )
{
*j=n;m=(p+n)->wei;
}
n=n+1;
}
if((*i)>(*j)) { n=(*i);*i=(*j);*j=n;}
return;
}
struct hufnode *hufm (int n,int m,struct Input w[])
{
struct hufnode *p,*bh;
int k,i,j;
p=(struct hufnode*)malloc(m*sizeof(struct hufnode));
for(k=0;k<m;k++)
{
(p+k)->prt=NULL;
(p+k)->lch=NULL;
(p+k)->rch=NULL;
}
for(k=0;k<n;k++)
{
(p+k)->wei=w[k].total;
(p+k)->ch=w[k].ch;
}
for(k=n;k<m;k++)
{
myselect(p,k,&i,&j);
(p+i)->prt=(p+k); (p+j)->prt=(p+k);
(p+k)->lch=(p+i); (p+k)->rch=(p+j);
(p+k)->wei=(p+i)->wei+(p+j)->wei;
}
bh=p+m-1;
return (bh);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -