用名单设计一个哈希表c语言
时间: 2023-08-15 08:27:38 浏览: 32
好的,以下是一个简单的哈希表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;
int size;
} HashTable;
unsigned int hash(const char* key) {
unsigned int hash = 0;
unsigned int i;
for (i = 0; i < strlen(key); ++i) {
hash += key[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
HashTable* create_table(int size) {
HashTable* table = (HashTable*)malloc(sizeof(HashTable));
table->nodes = (HashNode**)calloc(size, sizeof(HashNode*));
table->size = size;
return table;
}
void free_table(HashTable* table) {
int i;
for (i = 0; i < table->size; ++i) {
HashNode* node = table->nodes[i];
if (node != NULL) {
free(node->key);
free(node->value);
free(node);
}
}
free(table->nodes);
free(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) {
if (strcmp(node->key, key) == 0) {
free(node->value);
node->value = strdup(value);
return;
}
node = node->next;
}
HashNode* new_node = (HashNode*)malloc(sizeof(HashNode));
new_node->key = strdup(key);
new_node->value = strdup(value);
new_node->next = table->nodes[index];
table->nodes[index] = new_node;
}
char* get(HashTable* table, const char* key) {
unsigned int index = hash(key) % table->size;
HashNode* node = table->nodes[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return NULL;
}
int main() {
HashTable* table = create_table(TABLE_SIZE);
set(table, "key1", "value1");
set(table, "key2", "value2");
printf("%s\n", get(table, "key1"));
printf("%s\n", get(table, "key2"));
free_table(table);
return 0;
}
```
这个哈希表使用了链表法解决冲突,具体实现细节可以参考代码注释。