C程序简单实现哈夫曼树的编码

#include "stdio.h"
#include "string.h"
typedef struct
{
float weight;/*用来存放各个结点的权值*/
unsigned int parent,Lchild,Rchild;/*指向双亲 孩子结点的指针*/
}HTNode,*HuffmanTree;/*动态分配数组,存储哈夫曼树*/
typedef char * *HuffmanCode;
HuffmanTree *ht=NULL;
HuffmanCode *hc=NULL;
CrtHuffmanTree(/*HuffmanTree *ht,HuffmanCode *hc,*/float w[],int n)
{int i,s1,s2,c,m,start,p;
char *cd;
m=2*n-1;
*ht=(HuffmanTree)malloc((m+1)*sizeof(HTNode));
for(i=1;i<=n;i++)
{
  (*ht)[i].weight=w[i];
  (*ht)[i].parent=0;
  (*ht)[i].Lchild=0;
  (*ht)[i].Rchild=0;
}
for(i=n+1;i<=m;i++)
{
  (*ht)[i].weight=0;
  (*ht)[i].parent=0;
  (*ht)[i].Lchild=0;
  (*ht)[i].Rchild=0;
}
for(i=n+1;i<=m;i++)
{
   Select(/*ht,*/i-1,&s1,&s2);
    (*ht)[s1].parent=i;(*ht)[s2].parent=i;
    (*ht)[i].Lchild=s1;(*ht)[i].Rchild=s2;
    (*ht)[i].weight=(*ht)[s1].weight+(*ht)[s2].weight;
}
*hc=(HuffmanCode)malloc((n+1)*sizeof(char *));
cd=(char *)malloc(n*sizeof(char));
cd[n-1]='/0';
for(i=1;i<=n;i++)
{
   start=n-1;
  for(c=i,p=(*ht)[i].parent;p!=0;c=p,p=(*ht)[p].parent)

      if((*ht)[p].Lchild==c)
  cd[--start]='0';
else cd[--start]='1';

    (*hc)[i]=(char *)malloc((n-start)*sizeof(char));
     strcpy((*hc)[i],&cd[start]);
printf("/nThe code of the %d is:",i);
printf("%s./n",(*hc)[i]);
   printf("/n------------");
}
free(cd);
}
Select(/*HuffmanTree *ht,*/int g,int s1,int s2)
{
  int j,k,m,n;
    for(k=1;k<=g;k++)
     {
      if((*ht)[k].parent==0)
{
  s1=k;
  break;
}
      }
   for(j=1;j<=g;j++)
   {
    if(((*ht)[j].weight<(*ht)[k].weight)&&((*ht)[j].parent==0))
       s1=j;
   }

     for(m=1;m<=g;m++)
      {
if(((*ht)[m].parent==0)&&(m!=s1))
{
   s2=m;
   break;
  }
      }
      for(n=1;n<=g;n++)
     {
       if(((*ht)[n].weight<(*ht)[m].weight)&&((*ht)[n].parent==0)&&(n!=s1))
s2=n;
     }
}
main()
{
int i,n;
float w[20];

printf("Please input the number of the datas:/n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{printf("Please input the datas:/n");
    scanf("%f",&w[i]);
}
CrtHuffmanTree(/*ht,hc,*/w,n);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值