哈夫曼树的构造、权值 C语言代码实现
一、数据结构
(1)树的数据结构
typedef struct
{
int data;
int left, rigth, parent;
}HTNode,*HTree;
(2)排序链表的数据结构
typedef struct SNode
{
int data;//存放weight值
int Tnum;//存放结点在树中的编码
struct SNode *next;
}SNode,*SString;
二、构造哈夫曼树
//Select的参数k:T中有k个带权值的结点
int Select(HTree T, int k, int& the1, int &the2)
{
//声明新链表,用于存储待处理结点的数据、排序
SString blue;
blue = (SNode*)malloc(sizeof(SNode));
SNode* head = blue;
for (int i = 1; i <= k; i++)
{
if (T[i].parent==0)
{
SString t =(SNode*)malloc(sizeof(SNode));
t->data = T[i].data;
t->Tnum = i;
t->next = NULL;
head->next = t;
head = t;
}
}
head = blue->next;
printf("待排序表中各节点的weight值如下:\n");
PrintList(blue);
//根据链表中的weigth排序得到升序链表
SString temp1 = blue->next;
SString temp2 = temp1;
for (int i = 1;temp1; i++)
{
temp2 = temp1;
for (int j=i+1;temp2->next ; j++)
{
if ((temp2->data) >= (temp2->next->data))
{
int td, tt;
td = temp2->data;
temp2->data = temp2->next->data;
temp2->next->data = td;
tt = temp2->Tnum;
temp2->Tnum = temp2->next->Tnum;
temp2->next->Tnum = tt;
}
temp2 = temp2->next;
}
temp1 = temp1->next;
}
printf("排序后表中各节点的weight值如下:\n");
PrintList(blue);
the1 = head