【问题标题】:How to save memory inside hashtable?如何在哈希表中节省内存?
【发布时间】:2019-02-12 08:58:33
【问题描述】:

在我的结构 struct ListNode 中,我正在制作一个 int 类型的变量键,但有必要在 struct Listnode 中制作它,我们可以在 HashTableNode 中制作它,因为当 HashTableNode 中有两个或更多项目时(即单个表节点中的冲突会更多)而不是我们必须创建更多的链表节点,并且如果我们可以在 HashTableNode 中定义它,那么每次在该节点键变量内部都会消耗一些内存,而不是我们可以节省内存。

在每个列表节点中提及键是否正确,以便我们可以随时访问,因为下面的哈希表实现来自非常著名的数据结构书。

请告诉我我上面提到的是正确的
因为我是初学者如果不是那么请纠正我

#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;
 }
int HASH(int  data,int tsize){
return(data%tsize);
}
/// 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;
}

【问题讨论】:

    标签: c data-structures hash


    【解决方案1】:

    必须为每个节点存储密钥,因为它用于解决冲突。请注意,冲突发生在 hash valuenot key,这意味着同一桶 (HashTableNode) 中的每个元素 (Listnode) 仍然会有一个不同的键,所以你不能优化它。

    但是,在您的示例中数据是关键(通常称为 HashSet 而不是 HashMap),因此实际上不需要 Listnode 中的 key 字段.

    【讨论】:

    • 我对@9​​87654325@ 和index 感到困惑,因为在我的代码中,键被分配给索引,你能解释一下吗
    • @david12345,请查看更新后的答案。此外,索引存储到 key 字段这一事实对我来说也没有任何意义。
    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2016-06-27
    相关资源
    最近更新 更多