|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define Maxsize 100
typedef struct{
unsigned int weight;
unsigned int parent,lchild,rchild;
}HTNode,*HuffmanTree;
typedef char * *HuffmanCode;
void Select(HuffmanTree HT,int n,int &s1,int &s2) //选出权值最小的的两个结点
{
int i;
s1=s2=0;
for(i=1;i<=n;i++){
if(HT[i].weight<HT[s2].weight && HT[i].parent==0&&s2!=0){
if(HT[i].weight<HT[s1].weight) {
s2=s1;
s1=i;
}
else s2=i;
}
if((s1==0||s2==0)&&HT[i].parent==0){
if(s1==0)
s1=i;
else if(s2==0) {
if(HT[i].weight<HT[s1].weight) {
s2=s1;
s1=i;
}
else s2=i;
}
}
}
}
void HuffmanCoding(HuffmanTree &Ht,HuffmanCode &HC,int *w,int n){
if(n<=1)
return ;
int m=2*n-1;
HuffmanTree HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode));
HuffmanTree p;
int i;
for(p=HT,i=1;i<=n;++i,++p,++w){//初始化n个结点
//*p={*w,0,0,0,0};
p->weight=*w;
p->lchild=0;
p->parent=0;
p->rchild=0;
}
for(;i<=m;i++,++p){
// *p={0,0,0,0};
p->weight=0;
p->lchild=0;
p->parent=0;
p->rchild=0;
}
for(i=n+1;i<=m;++i){//// 建哈夫曼树
int s1,s2;
Select(HT,i-1,s1,s2);
HT[s1].parent=i;
HT[s2].parent=i;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
HC=(HuffmanCode)malloc((n+1)*sizeof(char*));
char* cd=(char*)malloc(n*sizeof(char));
cd[n-1]='\0';
for(i=1;i<=n;++i){
int start=n-1;
for(int c=i,int f=HT[i].parent;f!=0;c=f,f=HT[f].parent)//逆序编码哈夫曼树
if(HT[f].lchild==c)////////////
cd[--start]='0';
else
cd[--start]='1';
HC[i]=(char*)malloc((n-start)*sizeof(char));
strcpy(HC[i],&cd[start]);
}
free(cd);
}
void OutputHuffmanCode(HuffmanTree HT,HuffmanCode HC,int n)
{
int i;
printf("\nnumber---weight---huffman code\n");
for(i=1;i<=n;i++)
printf(" %d %d \n",HT[i].weight,HC[i]);
}
int main(){
HuffmanTree HT;
int n,w[Maxsize];
printf("请输入你要创建的哈夫曼树的节点的个数:\n");
scanf("%d",&n);
HT=(HuffmanTree)malloc(sizeof(HTNode)*n);
char number;
for(int i=0;i<n;i++){
printf("请输入各节点的权值");
scanf("%d",&w[i]);
}
HuffmanCode HC;
HuffmanCoding(HT,HC,w,n);
OutputHuffmanCode(HT,HC,n);
/*for(i=1;i<=n;i++){
printf("%s\n",HC[i]);
}*/
return 0;
}
|
|