如何编写一个C语言的hash表

   2024-10-02 5280
核心提示:下面是一个简单的C语言实现的hash表示例:#include stdio.h#include stdlib.h#include string.h#define SIZE 100typedef struct

下面是一个简单的C语言实现的hash表示例:

#include <stdio.h>#include <stdlib.h>#include <string.h>#define SIZE 100typedef struct Node {    char key[50];    int value;    struct Node* next;} Node;Node* hashtable[SIZE];unsigned int hash(const char* key) {    unsigned int hash = 0;    for (int i = 0; key[i] != '\0'; i++) {        hash = hash * 31 + key[i];    }    return hash % SIZE;}void insert(const char* key, int value) {    unsigned int index = hash(key);    Node* newNode = (Node*)malloc(sizeof(Node));    strcpy(newNode->key, key);    newNode->value = value;    newNode->next = hashtable[index];    hashtable[index] = newNode;}int get(const char* key) {    unsigned int index = hash(key);    Node* current = hashtable[index];    while (current != NULL) {        if (strcmp(current->key, key) == 0) {            return current->value;        }        current = current->next;    }    return -1;}int main() {    insert("apple", 5);    insert("banana", 10);    printf("Value of apple is %d\n", get("apple"));    printf("Value of banana is %d\n", get("banana"));    return 0;}

这个例子中,我们使用一个固定大小的数组hashtable来保存hash表的数据。我们使用一个简单的hash函数来计算key的hash值,并用该值来确定key在数组中的位置。在插入数据时,我们首先根据key计算hash值,然后创建一个新的节点,并将其插入到对应位置的链表中。在查找数据时,我们同样根据key计算hash值,然后遍历对应位置的链表,找到对应的节点并返回其值。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号