我尝试在c中创建带有链表的哈希表,
首先结构代码是:
我定义尺寸:
和哈希函数
最后插入的代码是:
然后创建一个struct数组
这是主要内容:
#include <stdlib.h>
#include <stdio.h>
typedef struct citizens * data ;
struct citizens
{
int id, age ;
char *name ;
char gender ;
data next ;
};
#define hash_size 50
data hash_table [hash_size] ;
int hash_function(int key)
{
return key % hash_size ;
}
void insert_to_hash (int key_id, char *name, int age, char gender)
{
data item = (data)malloc(sizeof(struct citizens)) ;
data postion ;
item->id = key_id ;
item->age = age ;
item->name = name ;
item -> gender = gender ;
item ->next = NULL ;
int index = hash_function(key_id) ;
postion = hash_table [index] ;
if (item != NULL )
{
if (hash_table [index] ->next == NULL )
{
hash_table [index]->next = item ;
item ->next = NULL ;
}
else
{
while (postion ->next != NULL )
postion = postion->next ;
postion ->next = item ;
item ->next = NULL ;
}
}
else
printf("out of memory") ;
}
int main()
{
insert_to_hash(2, "ahmad" , 20, 'M') ;
return 0;
}
最佳答案
第 34 行:
if (item != NULL )
检查这个已经太晚了;您已经初始化了项目;你最可能的意思是:
if (position != NULL) {
/* leave code as is. */
} else {
hash_table[index] = item;
}
作为可读性说明,如下:
a[index]->thing
几乎普遍首选以下变体:
a [index]->thing
a[index] ->thing
a[index] -> thing
a [index] -> thing
...
一元 *、-、+、~、!、++、-- 和二进制 []、()、-> 周围的空格对于大多数读者来说在美观上没有吸引力。
关于在c中创建带有链表的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513175/