在c中创建带有链表的哈希表

标签 c data-structures hashtable

我尝试在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;
}

当我运行代码时,我没有收到任何错误或警告,编译器会像这样卡住: enter image description here

最佳答案

第 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/

相关文章:

c - C 中套接字的频繁读/写操作

python - 如何在 Python 中调试 C 编译器错误? (malloc 错误)

c - 即使我在主内存中还有很多空间,realloc 也会失败

python - 如何根据某些条件对单个可迭代对象进行 "round-robin"?

c - 代表一个迷宫

c - 通过 AS 的 incbin 指令包含的字符串上的 NULL 终止符

data-structures - 在 Redis 中将集合存储为散列值

c - int => int 映射的哈希函数

python - 为什么由不同初始化的集合构成的元组是相等的?

c - C 中关联集合的简单空间高效实现?