溫馨提示×

如何在C語言中使用hash表

小樊
88
2024-08-08 03:56:51
欄目: 編程語言

在C語言中實(shí)現(xiàn)hash表需要先定義一個(gè)結(jié)構(gòu)體來表示hash表的節(jié)點(diǎn),然后定義一個(gè)數(shù)組來存儲這些節(jié)點(diǎn),每個(gè)節(jié)點(diǎn)包含一個(gè)鍵值對,以及指向下一個(gè)節(jié)點(diǎn)的指針。下面是一個(gè)簡單的示例代碼:

#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;
}

在這個(gè)示例中,我們定義了一個(gè) hash 函數(shù)來計(jì)算鍵的哈希值,并使用鏈地址法來解決哈希沖突。我們可以通過 insert 函數(shù)來插入鍵值對,通過 get 函數(shù)來獲取鍵對應(yīng)的值。在 main 函數(shù)中演示了如何使用這個(gè)簡單的hash表。

0