新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

怎样在C语言中使用hash表,怎样在c语言中使用正弦函数

发布时间:2024-08-08 03:56:51

怎样在C语言中使用hash表

在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 ⑴;
}

int main() {
    insert("apple", 5);
    insert("orange", 10);
    insert("banana", 3);

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

    return 0;
}

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

tiktok粉丝购买:https://www.smmfensi.com/