c - 具有链接方法程序的哈希表未按预期工作

标签 c data-structures hash hashmap hashtable

我正在使用链表链接方法在 C 中实现哈希表。程序运行,但在搜索条目时,我总是得到结果 "Element is not found" 尽管元素在哈希中。这篇文章是对我之前的文章的轻微编辑。程序如下:

struct llist{
   char *s;
   struct llist *next;
};

struct llist *a[100];

void hinsert(char *str){
   int strint, hashinp;
   strint = 0;
   hashinp = 0;
   while(*str){
      strint = strint+(*str);
      str=str+1;
   }
   hashinp = (strint%100);
   if(a[hashinp] == NULL){
      struct llist *node;
      node = (struct llist *)malloc(sizeof(struct llist));
      node->s = str;
      node->next = NULL;
      a[hashinp] = node;
   }
   else{
      struct llist *node, *ptr;
      node = (struct llist *)malloc(sizeof(struct llist));
      node->s = str;
      node->next = NULL;
      ptr = a[hashinp];
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = node;
   }
}  

void hsearch(char *strsrch){
   int strint1, hashinp1;
   strint1 = 0;
   hashinp1 = 0;
   while(*strsrch){
      strint1 = strint1+(*strsrch);
      strsrch = strsrch+1;
   }
   hashinp1 = (strint1%100);
   struct llist *ptr1;
   ptr1 = a[hashinp1];
   while(ptr1 != NULL){
      if(ptr1->s == strsrch){
         cout << "Element Found\n";
         break;
      }else{
         ptr1 = ptr1->next;
      }
   }
   if(ptr1 == NULL){
      cout << "Element Not Found\n";
   }
}  

hinsert()是将元素插入到hash中,hsearch是在hash中搜索一个元素。哈希函数是在 hinsert() 本身中编写的。在 main() 中,我将 a[] 中的所有元素初始化为 NULL,如下所示:

for(int i = 0;i < 100; i++){
   a[i] = NULL;
}

最佳答案

您没有在此循环中推进指针。 (这也是一个非常糟糕的哈希函数)

while(*str){
        strint = strint+(*str);
}

关于c - 具有链接方法程序的哈希表未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13162990/

相关文章:

database - 如何跟踪、存储和遍历一个巨大的球形数据结构

ruby - 什么是哈希#count?

PowerShell 7.0 如何计算分块读取的大文件的哈希和

javascript - 文件的 JavaScript 中的快速低冲突非加密哈希

c - 使用 Malloc 并在函数之间分配给数组

c - R 的 C API 中的 SEXP 数据类型到底是什么,为什么要使用它?

c - 检测 objective-c PU 上的对齐内存要求

algorithm - 快速检查集合是否是存储集合的超集

c - 为什么以下两个语句的输出不同?

c++ - 搜索和更新整数值列表最快的数据结构是什么?