# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# include <string.h>
# include <limits.h>
/*
不等长的 哈夫曼前缀码(防止重码)
*/
//数据类型定义
typedef char **HuffmanCode;
typedef struct _HTNode
{
int weight;
int parent, lchild, rchild;
}HTNode, *HTree;
void Select_Min(const HTree T, int lenght, int *e1, int *e2 );
void Create_Huffman(HTree *T, int n); //创建哈夫曼树
HuffmanCode Create_HuffmanCode(const HTree HT, int n); //哈夫曼编码
HuffmanCode Create_HuffmanCode(const HTree HT, int n)
{
//HC不使用0号下标
HuffmanCode HC = (char **)malloc(sizeof(char*)*(n+1));//用于存放编码后的字符串
char* temp_string = (char*)malloc(sizeof(char)*n); // 次数组使用0号
temp_string[n-1] = '\0'; //数组第n个字符为‘\0’
for(int i=1; i<n+1; i++)
{ //逐个字符求哈夫曼编码
int parent = HT[i].parent;//需要回溯
int current = i;//回溯的当前结点
int start = n-1; //编码起点(逆向存入temp_string)
while(parent)
{//开始编码
if(current == HT[parent].lchild)
temp_string[--start] = '0';
else
temp_string[--start] = '1';
current = parent;
parent = HT[parent].parent;
} //编码结束之后形成的字符串存放HC中
HC[i] = (char*)malloc(sizeof(char)*(n-start));
strcpy(HC[i], &temp_string[start]);
}
free(temp_string);
return HC;
}
//前置函数,选取两个结点最小值
void Select_Min(const HTree T, int lenght, int *e1, int *e2 )
{
int min1, min2;
min1 = min2 = INT_MAX;
int pos1, pos2;
pos1 = pos2 = 0;
for(int i=1; i<lenght+1; i++)
{
if(T[i].parent == 0)
{ //!parent == 0 说明在森林里
if(T[i].weight < min1)
{
min2 = min1;
pos2 = pos1;
min1 = T[i].weight;
pos1 = i;
}
else if (T[i].weight < min2)
{
min2 = T[i].weight;
pos2 = i;
}
}
}
*e1 = pos1;
*e2 = pos2;
}
void Create_Huffman(HTree *T, int n)
{
if (n <= 1)
return;
int m = 2*n - 1; //一共产生m个结点
*T = (HTree)malloc(sizeof(HTNode) * (m+1)); //0号位置不用
for(int k=1; k<m+1; k++)
{ //Step1:初始化
(*T)[k].lchild = (*T)[k].rchild = 0;
(*T)[k].parent = 0;
}
for(int i=1; i<n+1; i++)
{ //输入权值
scanf(" %d", &(*T)[i].weight);
}
//Step2:创建哈夫曼树
int min1, min2; //最小和次小
for (int j=n+1; j<m+1; j++)
{
Select_Min(*T, j-1, &min1, &min2); //核心语句
(*T)[min1].parent = (*T)[min2].parent = j;
(*T)[j].lchild = min1; //设置左孩子
(*T)[j].rchild = min2; //设置右孩子
(*T)[j].weight = (*T)[min1].weight + (*T)[min2].weight; //权值相加生新树
}
}
哈夫曼树编码的实现
最新推荐文章于 2024-10-08 00:02:21 发布