【问题标题】:Searching a linked list using hash search使用哈希搜索搜索链表
【发布时间】: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


【解决方案1】:

您似乎错过了散列的基本概念,以及它在hash table 数据结构中的常用用法。请仔细阅读。

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

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

【讨论】:

  • 我研究过哈希表,并尝试通过上面的代码来实现。它给出了分段错误。请仔细检查并让我知道错误。谢谢
  • 好吧,在调试器中运行它,至少告诉我们在哪里它出现了段错误。
  • 调试器在第一个 if(condition) 函数 ht_set 中给出 seg 错误
猜你喜欢
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
  • 2012-10-12
  • 2010-09-08
  • 1970-01-01
  • 2014-04-07
  • 2014-11-21
  • 2013-04-27
相关资源
最近更新 更多