写一个哈希表的C++代码
时间: 2023-04-09 17:01:46 浏览: 76
好的,以下是一个简单的哈希表的C代码:
```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* create_table() {
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;
}
}
void free_table(HashTable* table) {
for (int i = 0; i < TABLE_SIZE; i++) {
HashNode* node = table->nodes[i];
while (node != NULL) {
HashNode* next = node->next;
free(node->key);
free(node->value);
free(node);
node = next;
}
}
free(table->nodes);
free(table);
}
int main() {
HashTable* table = create_table();
set(table, "apple", "red");
set(table, "banana", "yellow");
set(table, "grape", "purple");
printf("%s\n", get(table, "apple"));
printf("%s\n", get(table, "banana"));
printf("%s\n", get(table, "grape"));
printf("%s\n", get(table, "orange"));
free_table(table);
return 0;
}
```
这个代码实现了一个简单的哈希表,可以存储字符串类型的键值对。哈希函数使用了一个简单的算法,将每个字符的 ASCII 码乘以一个固定的质数,然后相加得到哈希值。如果发生哈希冲突,使用链表法解决。