所以我正在尝试编写一个返回新制作的Huffman树的函数,该函数在列表中找到两个最小的频率然后删除它们(remove_smallest)然后使它们成为新的treeNode(root)的子节点再次将它插入列表中(采用霍夫曼树的风格)并完成所有操作,直到列表中剩下1个元素。在第二次调用remove_smallest函数之后,我的程序似乎正在崩溃。 remove_smallest函数返回列表中最小的treeNode它应该继续运行,直到剩下一个元素。我哪里错了?我为什么会出现分段错误?正如我所提到的,在两次调用remove_smallest之后,它似乎正在崩溃。
我是否取消引用指向随机内存的指针?或设置不正确的指针?
感谢任何帮助。谢谢。
代码:
typedef TreeNode* Element;
typedef Frequency* TreeElement;
struct TreeNode {
TreeElement data; //stores a pointer to the data in this tree node
TreeNode *left; //reference to the left child tree
TreeNode *right; //reference to the right child tree
};
struct ListNode {
Element data; // stores a pointer to data in node
ListNode *next; // reference to next node in list
};
struct List {
ListNode *head; // reference to the first node in the list
int numElements; // the number of nodes in the list
};
struct HuffmanTree {
TreeNode *root;
};
struct FrequencyList {
List *freqs;
};
struct Frequency {
char data; // the character being represented
int count; // the number of occurrences of the character
};
HuffmanTree *createHuffmanTree(FrequencyList *frequencies) {
List * newList = new List;
newList = frequencies->freqs;
TreeNode * newTree1;
TreeNode * newTree2;
TreeNode * root = new TreeNode;
while (frequencies->freqs->numElements != 1) {
newTree1 = remove_smallest(frequencies); // removes and returns smallest treeNode from list
newTree2 = remove_smallest(frequencies);
root->data->count = newTree1->data->count + newTree2->data->count;
root->left = newTree1;
root->right = newTree2;
insert(newList, root); // inserts back into list
}
HuffmanTree * newHuffmanTree = new HuffmanTree;
newHuffmanTree->root = root;
return newHuffmanTree;
}
答案 0 :(得分:0)
分段错误是由于尝试访问不存在的内存而引起的。对于不熟悉C / C ++的人来说,这是一个非常常见的错误。我会仔细检查你的所有指针,并确保你试图访问你想要的信息(地址/价值)。