-1
所以我做了一個函數來建立一個霍夫曼樹,它是按照頻率遞增的順序傳遞一個鏈表(在每個節點內分配一個值),但它似乎卡住時直到最後一個'非內部節點',就像鏈接列表中的一個節點,該鏈接列表中有一個字符開頭。霍夫曼樹卡在最後一個非內部節點
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)