繁体   English   中英

如何在哈希函数中更新表大小

[英]how to update table size inside hash function

我正在学习如何实现哈希表,但在这里我有点困惑,因为在下面的书中可以找到代码,而且我对代码的理解也很充分,但是在书中没有定义HASH函数,我知道我们必须通过定义它拥有,但是根据下面被给给予书内码HASH正在两个参数无论我使用的HASHHashInsert它正在采取两个参数index=HASH(data,t->size)如果我们假设的那返回类型HASH现在为int例如,我们可以将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;
}

我只是在学习哈希的实现,所以主要看起来很安静很奇怪

int main(){
  return 0;
}

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

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

因此,您可以将大小取模,而不是固定的幻数 7

return(data%tsize);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM