首页 > 解决方案 > 在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;
}

当我运行代码时,我没有收到任何错误或警告,编译器会像这样卡住: 在此处输入图像描述

标签: cdata-structureshashtable

解决方案


在第 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
...

一元 *,-,+,~,!,++,-- 和二元 [], (), -> 周围的空格在美学上对大多数读者没有吸引力。


推荐阅读