gpt4 book ai didi

c - 如何从 C 中的链表构建霍夫曼树?

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:49 25 4
gpt4 key购买 nike

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

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则为双链表,从代码看不清楚为什么需要link。插入时,rlink 和 link 应该被使用,在插入点前一个节点和下一个节点都必须安排它们的 rlink 和 link。

关于c - 如何从 C 中的链表构建霍夫曼树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53263923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com