如何用C语言从链表中构建huffman树



我有一个排序的链表,但我尝试了以下代码来创建一个树并打印它。但我无法获得输出。。

NODE insertorder(NODE first,int pixel,int freq, NODE llink,NODE rlink)
{
NODE temp=(NODE)malloc(sizeof(struct node));
NODE cur,prev=NULL;
temp->pix=pixel;
temp->freq=freq;
temp->llink=llink;
temp->rlink=rlink;
temp->link=NULL;
if(first==NULL)
return temp;
cur=first;
while(cur!=NULL&&freq>cur->freq)
{
prev=cur;
cur=cur->link;
}
temp->link=cur;
if(prev!=NULL)
prev->link=temp;
return first;
}
void roots(NODE first)
{
NODE t1=first,t2=first->link;//taking first two elements in the list everytime
if(t2!=NULL)
createtree(t1,t2);
}
void createtree(NODE first,NODE nxt)
{
NODE temp=(NODE)malloc(sizeof(struct node));
temp->pix=0;
temp->freq=first->freq+nxt->freq;
temp->llink=first;
temp->rlink=nxt;
temp->link=NULL;
first=deletefirst(first);
first=deletefirst(first);
//inserting back the new sum of both elements into the same list
first=insertorder(first, temp->pix, temp->freq, temp->llink, temp->rlink); 
roots(first);//calling root back
}
printleaf(NODE first,int a[500],int current)
{
if(first->llink!=NULL)
{
a[current]=0;
printleaf(first->llink,a,current+1);
}
if(first->rlink!=NULL)
{
a[current]=1;
printleaf(first->rlink,a,current+1);
}
if(first->llink==NULL&&first->rlink==NULL)
for(int i=0;a[i]!='';i++)
printf("%d",a[i]);
}    

我的想法是将树根存储回以前的列表中,但当我执行它时,我没有得到输出。

在链接列表中,如果有rlink和link,那么它就是双链接列表,从代码中不清楚为什么需要链接。插入时,应使用rlink和link,在插入点上,上一个节点和下一个节点都必须排列它们的rlink和链接。

最新更新