【发布时间】:2014-04-07 02:11:58
【问题描述】:
我是初学者。我从来没有做过哈希搜索。但现在,我只需要这样做。
我有一个链表,其中包含大约 3500 个随机整数,最高可达 100 万(1000000)个值。我想使用哈希搜索来搜索任何元素。
调试器在第一个 if(condition) 函数 ht_set 中给出 seg 错误。 请告诉我如何解决它? 这是我的代码:
typedef struct entry_s
{
int key;
int value;
struct entry_s *next1;
} entry_t;
typedef struct hashtable_s
{
int size;
entry_t **table;
}hashtable_t;
int ht_hash(hashtable_t *hashtable, int key)
{
int index;
index=key%hashtable->size;
return index;
}
entry_t *ht_newpair( int key, int value )
{
entry_t *newpair;
if((newpair = malloc( sizeof( entry_t)))== NULL || newpair->key == key || newpair->value==value)
return NULL;
newpair->next1 = NULL;
return newpair;
}
void ht_set( hashtable_t *hashtable, int key, int value )
{
int bin = 0;
entry_t *newpair = NULL;
entry_t *next1 = NULL;
entry_t *last = NULL;
bin = ht_hash(hashtable, key);
next1 = hashtable->table[bin];
while( next1 != NULL && key==next1->key)
{
last = next1;
next1 = next1->next1;
}
if( next1 != NULL || key==next1->key)
next1->value =value;
else
{
newpair = ht_newpair( key, value );
if( next1 == hashtable->table[ bin ] )
{
newpair->next1 = next1;
hashtable->table[ bin ] = newpair;
}
else if ( next1 == NULL )
last->next1 = newpair;
else
{
newpair->next1 = next1;
last->next1 = newpair;
}
}
}
谢谢
【问题讨论】:
-
听起来很有趣,但风险回报百分比太低,无法回应......
-
unsigned long int hashval; static int i = 0; hashval += i;hashval 未初始化。 (无论如何,该功能几乎没有意义) -
是的.. 好的,我会用一些值初始化它,比如 50。谢谢。还有什么??
标签: c linux hash linked-list