⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 zz00.txt

📁 哈夫曼编码的C程序代码 不知道是不是正确的 是我转载别人的程序
💻 TXT
字号:
#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);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -