我正在使用链表链接方法在 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/