首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

哈夫曼树里面的有关问题

2012-03-28 
哈夫曼树里面的问题~typedef struct Node{int weightint parent,LChild,RChild}HTNode,* HTreetypedef

哈夫曼树里面的问题~
typedef struct Node
{
 int weight;
 int parent,LChild,RChild;
}HTNode,* HTree;
typedef char * HuffmanCode;

void CreatHTree(HTree/*代表的是struct Node * 型,而不是struct Node */ ht,HuffmanCode hc,int * w,int n)
{//W存放n个权值,构造哈夫曼树 ht,并求出哈夫曼编码 hc
int start,i,m,s1,s2;
m=2*n-1;
ht=(HTree)malloc((m+1)* sizeof(HTNode));
for(i=1;i<=n;i++)
ht[i]={w[i],0,0,0};
for(i=n+1;i<=m;i++)ht[i]={0,0,0,0};//初始化
for(i=n+1;i<=m;i++)
{
 select(ht,i-1,&s1,&s2);
 //在 ht[1]~ht[i-1] 的范围内选择两个parent为0且weight最小的结点,其序号分别赋值给s1,s2返回,select函数要求
 //在上机调试是补充定义
 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 * 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]);
}
free(cd);
}
 
void select(HTree Sht,int n,int *S1,int *S2)
{
int i;
*S1=1;*S2=2;
for(i=2;i<=n;i++)
{
if(Sht[i].weight<Sht[*S1].weight)
{
*S2=*S1;*S1=i;
}
else if(Sht[i].weight<Sht[*S2].weight)
*S2=i;
}
}

select函数怎么弄啊,指针那些都乱掉了,,,谁帮我做一个select函数,结构要跟上面这个一样的啊,谢谢~~~

[解决办法]

探讨

还有啊,ht 不是 struct Node * 型的吗?那就应该是指针啊,为什么不是ht[s1]->parent而是ht[s1].parent?

热点排行