c语言

如何在C语言中使用hash表

小樊
88
2024-08-08 03:56:51
栏目: 编程语言

在C语言中实现hash表需要先定义一个结构体来表示hash表的节点,然后定义一个数组来存储这些节点,每个节点包含一个键值对,以及指向下一个节点的指针。下面是一个简单的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TABLE_SIZE 100

typedef struct Node {
    char key[100];
    int value;
    struct Node* next;
} Node;

Node* hashTable[TABLE_SIZE];

unsigned int hash(const char* key) {
    unsigned int hash = 0;
    while (*key) {
        hash = (hash * 31) + *key++;
    }
    return hash % TABLE_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("orange", 10);
    insert("banana", 3);

    printf("apple: %d\n", get("apple"));
    printf("orange: %d\n", get("orange"));
    printf("banana: %d\n", get("banana"));
    printf("grape: %d\n", get("grape"));

    return 0;
}

在这个示例中,我们定义了一个 hash 函数来计算键的哈希值,并使用链地址法来解决哈希冲突。我们可以通过 insert 函数来插入键值对,通过 get 函数来获取键对应的值。在 main 函数中演示了如何使用这个简单的hash表。

0
看了该问题的人还看了