C言語 ハッシュテーブル実装ガイド【初心者向けサンプルコード付き】
ハッシュテーブルを実装する基本的なステップは次のとおりです:
- ハッシュテーブルのデータ構造の定義:ハッシュテーブルのサイズ、バケットの数、バケットの構造などを含む。
- ハッシュ関数の実装:キーをバケットのインデックスにマッピングする。
- ハッシュテーブルの操作関数を実装する。挿入、検索、削除などの機能を含む。
- キーコンフリクトの処理: 複数のキーが同じバケツにマップされる場合、リンクリストやオープンアドレッシングなどの方法を使用して処理する必要があります。
以下は、ハッシュテーブルを実装するための簡単なC言語のサンプルコードです。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 10
typedef struct Node {
char* key;
int value;
struct Node* next;
} Node;
Node* table[TABLE_SIZE];
int hash_function(char* key) {
int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash += key[i];
}
return hash % TABLE_SIZE;
}
void insert(char* key, int value) {
int index = hash_function(key);
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->key = key;
new_node->value = value;
new_node->next = table[index];
table[index] = new_node;
}
int search(char* key) {
int index = hash_function(key);
Node* current = table[index];
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
return current->value;
}
current = current->next;
}
return -1; // key not found
}
void delete(char* key) {
int index = hash_function(key);
Node* current = table[index];
Node* prev = NULL;
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
if (prev == NULL) {
table[index] = current->next;
} else {
prev->next = current->next;
}
free(current);
return;
}
prev = current;
current = current->next;
}
}
int main() {
insert("apple", 5);
insert("banana", 10);
printf("Value of apple: %d\n", search("apple"));
printf("Value of banana: %d\n", search("banana"));
delete("apple");
printf("Value of apple after deletion: %d\n", search("apple"));
return 0;
}
このコードは、簡単なハッシュテーブルを実装し、挿入、検索、削除の操作を含みます。この例では、ハッシュ関数は文字のASCIIコードの合計を使用してハッシュ値を計算し、衝突の処理にリストを使用しています。この例を自分のニーズに合わせて修正や拡張することができます。