c - 在c中创建带有链表的哈希表
问题描述
我试图用c中的链表创建哈希表,
首先结构代码是:
我定义大小:
哈希函数
最后插入代码是:
然后创建一个结构数组,
这是主要的:
#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# - 如何让 OpenApi Generator 转换字典
正确吗? - sql - JPQL 选择公司、分公司、部门或部门层次结构的部分
- spring-boot - 休息模板 | 带有 SSL 的 HttpClient 无法设置连接池属性
- c++ - MIDI format1 -> MFC 中的 format0 转换器
- node.js - localtunnel 和 CORS 无法正常工作
- python - 如何读取excel电子表格并验证数据类型,并打印数据类型错误或为空的数据类型?
- ios - 不包括 testflight 中的 opencv2.framework
- python - 读取 csv 时将所有值转换为字符串
- python - 本地主机上的 docker setup 站点没有响应或无法连接
- kubernetes - 更新容器时如何知道升级我的 pod?