gpt4 book ai didi

c - 如何更新哈希函数内的表大小

转载 作者:行者123 更新时间:2023-11-30 18:34:28 26 4
gpt4 key购买 nike

我正在学习如何实现哈希表,但我在这里有点困惑,因为在下面的书中提供了代码,并且我对代码有足够的理解,但是在书中没有 HASH 的定义函数,我知道我们必须自己定义它,但是根据书中给出的以下代码 HASH 在我使用 HASH 的地方采用两个参数,如 HashInsert 如果我们假设 HASH 的返回类型为 int,则它需要两个参数 index=HASH(data,t->size)现在例如我们可以将 HASH 定义为

int HASH(int  data,int tsize){
return(data%7);
}

但是根据我的程序,我应该如何更新HASH函数内的t->size(表大小)或者我应该如何使用它请帮助我正确实现上述 HASH 函数

#define Load_factor 20
#include<stdio.h>
#include<stdlib.h>
struct Listnode{
int key;
int data;
struct Listnode* next;
};
struct HashTableNode{
int bcount; /// Number of elements in block
struct Listnode* next;
};
struct HashTable{
int tsize; /// Table size
int count;
struct HashTableNode** Table;
};
struct HashTable* createHashTable(int size){
struct HashTable* h;
h=(struct HashTable*)malloc(sizeof(struct HashTable));
h->tsize=size/Load_factor;
h->count=0;

h->Table=(struct HashTableNode**)malloc(sizeof(struct HashTableNode*)*h->tsize);
if(!h->Table){
printf("Memory Error");
return NULL;
}
for(int i=0;i<h->tsize;i++){
h->Table[i]->bcount=0;
h->Table[i]->next=NULL;
}
return h;
}

/// Hashsearch
int HashSearch(struct HashTable* h,int data){
struct Listnode* temp;
temp=h->Table[HASH(data,h->tsize)]->next;
while(temp) ///same as temp!=NULL
{
if(temp->data==data)
return 1;
temp=temp->next;
}
return 0;

}

int HashDelete(struct HashTable* h,int data)
{
int index;
struct Listnode *temp,*prev;
index=HASH(data,h->tsize);
for(temp=h->Table[index]->next,prev=NULL;temp;prev=temp,temp=temp->next)
{
if(temp->data==data)
{
if(prev!=NULL)
prev->next=temp->next;
free(temp);
h->Table[index]->bcount--;
h->count--;
return 1;
}
}

return 0;

}
int HashInsert(struct HashTable *h ,int data){
int index;
struct Listnode* temp,*newnode;
if(HashSearch(h,data))
return 0;
index = HASH(data,h->tsize);
temp=h->Table[index]->next;
newnode=(struct Listnode*)malloc(sizeof(struct Listnode));
if(!newnode)
return -1;
newnode->key=index;
newnode->data;
newnode->next=h->Table[index]->next;
h->Table[index]->next=newnode;
h->Table[index]->bcount++;
h->count++;
return 1;
}

i am just learning implementation of hashing so main is looking quiet weird

int main(){
return 0;
}

最佳答案

不应该!我的意思是你不修改它。

相反,该函数获取哈希表的大小(“存储桶”的数量),以便它可以使用它从哈希值创建存储桶索引。这通常是通过模%来完成的。

所以不是固定的 magic number 7 对大小取模:

return(data%tsize);

关于c - 如何更新哈希函数内的表大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52204225/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com