【问题标题】:how to build huffman tree from a linked list in C?如何从 C 中的链表构建霍夫曼树?
【发布时间】:2018-11-12 14:10:10
【问题描述】:

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

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

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

【问题讨论】:

  • insertorder 缺失,请提供最小完整且可验证的示例stackoverflow.com/help/mcve
  • 我已经添加了 insertorder 功能
  • 您需要提供一个可复制的案例,带有一个主。描述预期的结果和你得到的结果。

标签: c list tree traversal huffman-code


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多