[英]how to build huffman tree from a linked list in C?
我有一個排序的鏈表,但是我嘗試了以下代碼來創建樹並打印。 但是我無法獲得輸出。
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]!='\0';i++)
printf("%d",a[i]);
}
我的想法是將樹根存儲回以前存在的相同列表中,但是當我執行它時,我沒有得到輸出。
在鏈接列表中,如果存在rlink和link,則它是雙鏈接列表,並且從代碼中尚不清楚為什么需要鏈接。 插入時,應使用rlink和link,在插入點上一個節點和下一個節點都必須安排其rlink和link。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.