使用C语言写一个hash表
时间: 2023-05-12 10:03:48 浏览: 108
好的,以下是一个简单的C语言实现的hash表:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct {
char* key;
char* value;
} HashNode;
typedef struct {
HashNode** nodes;
} HashTable;
unsigned int hash(const char* key) {
unsigned int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash = hash * 31 + key[i];
}
return hash;
}
HashTable* createHashTable() {
HashTable* table = malloc(sizeof(HashTable));
table->nodes = calloc(TABLE_SIZE, sizeof(HashNode*));
return table;
}
void set(HashTable* table, const char* key, const char* value) {
unsigned int index = hash(key) % TABLE_SIZE;
HashNode* node = table->nodes[index];
while (node != NULL && strcmp(node->key, key) != 0) {
node = node->next;
}
if (node == NULL) {
node = malloc(sizeof(HashNode));
node->key = strdup(key);
node->next = table->nodes[index];
table->nodes[index] = node;
}
node->value = strdup(value);
}
char* get(HashTable* table, const char* key) {
unsigned int index = hash(key) % TABLE_SIZE;
HashNode* node = table->nodes[index];
while (node != NULL && strcmp(node->key, key) != 0) {
node = node->next;
}
if (node == NULL) {
return NULL;
} else {
return node->value;
}
}
int main() {
HashTable* table = createHashTable();
set(table, "apple", "red");
set(table, "banana", "yellow");
set(table, "grape", "purple");
printf("apple is %s\n", get(table, "apple"));
printf("banana is %s\n", get(table, "banana"));
printf("grape is %s\n", get(table, "grape"));
return 0;
}
```
这个hash表使用了链表来解决hash冲突的问题,每个节点包含一个键和一个值。使用`set`函数可以向hash表中添加一个键值对,使用`get`函数可以根据键获取对应的值。
阅读全文