我正在使用链表链接方法在 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()
是将元素插入散列,并hsearch
在散列中搜索元素。哈希函数是写在hinsert()
自己里面的。在中main()
,我将所有元素初始化a[]
为NULL
如下所示:
for(int i = 0;i < 100; i++){
a[i] = NULL;
}