在C

时间:2017-11-27 04:32:37

标签: c

我目前正在尝试从排序的优先级列表中创建Huffman树。

排序列表和Huffman树具有相同的结构:

typedef struct _TreeNode{
    unsigned char ch;
    int freq;
    struct _TreeNode* left;
    struct _TreeNode* right;
    struct _TreeNode* next;
} TreeNode;

尝试从优先级列表创建树时,我使用以下代码:

TreeNode* create_tree(TreeNode* priority_list){
    while(priority_list -> next != NULL){
        TreeNode* root = malloc(sizeof(*root));
        root -> left = pop_tree(&priority_list);
        root -> right = pop_tree(&priority_list);
        root -> freq = (root -> left -> freq) + (root -> right -> freq);
        priority_list = enqueue_tree(priority_list, root);
    }
    return priority_list;
}

TreeNode* pop_tree(TreeNode** pq){
    TreeNode* popped = *pq;
    *pq = (*pq) -> next;
    popped -> next = NULL;
    return popped;
}

TreeNode* enqueue_tree(TreeNode* pq, TreeNode* new_node){
    if(new_node -> freq < pq -> freq){
        new_node -> next = pq;
        return new_node;
    }
    TreeNode* curr = pq;
    TreeNode* temp = pq;
    while(curr -> next != NULL && (curr -> freq <= new_node -> freq)){
        temp = curr;
        curr = curr -> next;
    }
    new_node -> next = curr;
    temp -> next = new_node;
    return pq;
}

enqueue_tree函数类似于用于创建初始排序priority_list的函数,输出正确。但是,当我运行此代码时,它似乎陷入无休止的循环中。 pop_tree是来自先前代码的修改函数,该代码用于简单链接列表,并按预期工作,但可能是问题。所以,我的问题是,什么可能导致分段错误/无限循环?

0 个答案:

没有答案