使用哈希搜索搜索链接列表

时间:2014-03-05 06:51:29

标签: c linux hash linked-list

我是初学者。我从未做过哈希搜索。但现在,我必须这样做。

我有一个包含大约3500个随机整数的链表,最多可达10万(1000000)。我想使用哈希搜索来搜索任何元素。

调试器首先在函数ht_set中给出seg错误if if(condition)。 请告诉我如何解决? 这是我的代码:

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;
          }
    }
}

由于

1 个答案:

答案 0 :(得分:2)

你似乎错过了哈希的基本思想,它是如何在hash table数据结构中常用的。请仔细阅读。

基本上,搜索链表时通常不使用哈希值;哈希用于构建表(数组)的索引,以便将内容快速映射到数组位置。

一些哈希表解决了与separate chaining的冲突,其中每个表槽都是所有已散列到同一位置的项目列表的头部。因此,当您搜索该列表时,您通过哈希搜索(请记住,列表中的所有项具有相同的哈希值),但要进行完全比较。

相关问题