霍夫曼树停留在最后的非内部节点

时间:2015-12-11 12:41:41

标签: c linked-list huffman-code

所以我已经建立了一个函数来构建一个霍夫曼树,它以频率的升序(每个节点中分配的值)传递一个链表,但是当它到达最后一个时它似乎卡住了# 39;非内部节点',如链接列表中的一个节点,该节点以一个字符开头。

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

当传递一个文本文件时,它将通过构建树来打印每次迭代,以显示添加两个节点,删除这些节点,以及插入新节点(两个先前节点频率加在一起),但它以当它只到达内部节点(标记为$)和一个非内部节点时出现seg故障。也就是说,经过多次迭代后,将其缩小到这个节点的数量:

$ : 4 $ : 4 $ : 4 z: 6 Segmentation fault (core dumped)

1 个答案:

答案 0 :(得分:1)

嗯,这里至少有一个bug:

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->nextNULL。然后输入循环体,并将temp替换为temp->next。现在temp->nextNULL。但是他们试图引用temp->next->frequencey。这是违反分段的行为。核心倾销。