我遇到了指针问题但无法绕过它..
在HashTable实现中,我有一个每个桶中有序节点的列表。我遇到的问题在插入函数中,在比较中查看下一个节点是否大于当前节点(为了插入该位置如果是)并保持订单。
你可能会发现这个哈希实现很奇怪,但是我需要能够进行大量的查找(但有时也很少)并计算重复次数(如果它已经插入)(所以我需要快速查找,因此哈希,我已经将自平衡树视为AVL或RB树,但我不知道它们所以我选择了解我知道如何实现的解决方案......它们对这类问题更快吗?),但我也是我完成后需要按顺序检索它们。 在我有一个简单的列表并且我将检索数组之前,然后执行QuickSort,但我想我可以通过保持列表的顺序来改进。
我必须映射它是一个27位无符号整数(最准确的是3 9位数字,但我将它们转换为27位数字(Sr <&lt; 18 | Sg&lt;&lt; 9 | Sb)同时它们的值为hash_value。如果你知道一个很好的函数将27位int映射到12-13-14位表请告诉我,我目前只是做典型的mod prime解决方案。
这是我的hash_node结构:
class hash_node {
public:
unsigned int hash_value;
int repetitions;
hash_node *next;
hash_node( unsigned int hash_val,
hash_node *nxt);
~hash_node();
};
这就是问题的根源
void hash_table::insert(unsigned int hash_value) {
unsigned int p = hash_value % tableSize;
if (table[p]!=0) { //The bucket has some elements already
hash_node *pred; //node to keep the last valid position on the list
for (hash_node *aux=table[p]; aux!=0; aux=aux->next) {
pred = aux; //last valid position
if (aux->hash_value == hash_value ) {
//It's already inserted, so we increment it repetition counter
aux->repetitions++;
} else if (hash_value < (aux->next->hash_value) ) { //The problem
//If the next one is greater than the one to insert, we
//create a node in the middle of both.
aux->next = new hash_node(hash_value,aux->next);
colisions++;
numElem++;
}
}//We have arrive to the end od the list without luck, so we insert it after
//the last valid position
ant->next = new hash_node(hash_value,0);
colisions++;
numElem++;
}else { //bucket it's empty, insert it right away.
table[p] = new hash_node(hash_value, 0);
numElem++;
}
}
这就是gdb所显示的:
Program received signal SIGSEGV, Segmentation fault.
0x08050b4b in hash_table::insert (this=0x806a310, hash_value=3163181) at ht.cc:132
132 } else if (hash_value < (aux->next->hash_value) ) {
这有效地表明我正在将内存地址与值进行比较,对吧? 希望很清楚。再次感谢!
答案 0 :(得分:2)
aux->next->hash_value
没有检查“next”是否为NULL。
答案 1 :(得分:1)
aux-&gt; next那时可能是NULL?我看不出你在哪里检查了aux-&gt; next是否为NULL。