简体   繁体   English

如何从C中的链表建立霍夫曼树?

[英]how to build huffman tree from a linked list in C?

i have a sorted linked list but and I've tried the following code to create a tree and print it. 我有一个排序的链表,但是我尝试了以下代码来创建树并打印。 But I'm unable to get the output.. 但是我无法获得输出。

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]);
    }    

My idea is to store back the tree root into the same list that was there before but when i execute it i did not get the output. 我的想法是将树根存储回以前存在的相同列表中,但是当我执行它时,我没有得到输出。

In link list if there are rlink and link then it is double link list and from code it is not clear why link is required. 在链接列表中,如果存在rlink和link,则它是双链接列表,并且从代码中尚不清楚为什么需要链接。 When inserting, rlink and link should be used where at insert point both previous node and next nodes has to arrange their rlink and link. 插入时,应使用rlink和link,在插入点上一个节点和下一个节点都必须安排其rlink和link。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM