因此,我创建了一个函数来构建哈夫曼树,该树按频率升序传递链表(每个节点内分配的值),但当它下降到最后一个“非内部节点”时,它似乎会卡住',就像在链表中的节点中一样,该节点被赋予了一个字符作为开头。
void build_tree(pqueue *list)
{
node *temp;
node* parent_node;
int min_1, min_2, ind = 0, counter = 0, length = 4;
temp = new_node();
while (length > 2)
{
temp = list -> start; /* 0. point temp at the linked list start (lowest frequency/letter) */
parent_node = new_node(); /* 1. make new node */
min_1 = temp -> frequency;
parent_node -> left = temp; /* 2. assign parent to point at left leaf */
temp = temp -> next; /* 3. move to next node */
min_2 = temp -> frequency;
parent_node -> right = temp; /* 4. assign parent to point at right leaf */
parent_node -> letter = '$';
parent_node -> frequency = min_1 + min_2; /* 5.assign internal node frequency */
list -> start = temp -> next;/* set the list to point at the next node for the next iteration through the loop */
while (ind == 0 && temp -> next != NULL)
{
temp = temp -> next;
if (temp -> next -> frequency >= parent_node -> frequency && temp != NULL) /* insert parent node */
{
parent_node -> next = temp -> next; /* parent points at higher freq node */
temp -> next = parent_node; /* parent node is temp next */
ind = 1;
}
else if (temp -> next == NULL) /* insert at end of list if parent node is biggest frequency */
{
temp -> next = parent_node;
ind = 1;
}
}
ind = 0;
temp = list -> start; /* temp points at new start (two nodes along)*/
while (temp -> next != NULL)
{
temp = temp -> next;
counter++;
printf("%c : %d\n", temp -> letter, temp -> frequency);
}
printf("----------------------------------------------\n");
length = counter;
counter = 0;
}
}
当传递一个文本文件时,它将打印构建树的每次迭代,以显示两个节点的添加、这些节点的删除以及新节点的插入(两个先前节点频率加在一起),但它以当它仅到达内部节点(标记为 $)和一个非内部节点时,会出现段错误。即,经过多次迭代才将其减少到这个节点数:
$:4
美元:4
美元:4
兹:6
段错误(核心转储)
最佳答案
好吧,这里至少有一个错误:
while (ind == 0 && temp -> next != NULL)
{
temp = temp -> next;
if (temp -> next -> frequency >= parent_node -> frequency && temp != NULL) /* insert parent node */
{
...
假设 temp->next
不是 NULL
,但 temp->next->next
是 NULL
。然后输入循环体,并将 temp
替换为 temp->next
。所以现在 temp->next
是 NULL
。但是您尝试引用 temp->next->frequencey
。这是分段违规。核心已转储。
关于c - 哈夫曼树卡在最后一个非内部节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34223853/