#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct {
char* key;
int value;
int isOccupied;
} HashItem;
HashItem table[TABLE_SIZE];
// 初始化哈希表
void init_table() {
for (int i = 0; i < TABLE_SIZE; i++) {
table[i].key = NULL;
table[i].value = 0;
table[i].isOccupied = 0;
}
}
// 哈希函数
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) {
int index = hash(key);
int originalIndex = index;
while (table[index].isOccupied == 1 && strcmp(table[index].key, key) != 0) {
index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
printf("哈希表已满!\n");
return;
}
}
if (table[index].isOccupied != 1) {
table[index].key = strdup(key);
table[index].value = value;
table[index].isOccupied = 1;
} else {
table[index].value = value;
}
}
// 查找函数
int get(const char* key) {
int index = hash(key);
int originalIndex = index;
while (table[index].isOccupied != 0) {
if (table[index].isOccupied == 1 && strcmp(table[index].key, key) == 0) {
return table[index].value;
}
index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
break;
}
}
return -1;
}
// 删除函数
void delete(const char* key) {
int index = hash(key);
int originalIndex = index;
while (table[index].isOccupied != 0) {
if (table[index].isOccupied == 1 && strcmp(table[index].key, key) == 0) {
free(table[index].key);
table[index].key = NULL;
table[index].isOccupied = -1;
printf("已删除 '%s'\n", key);
return;
}
index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
break;
}
}
printf("未找到键 '%s'。\n", key);
}
int main() {
init_table();
// 插入测试数据
insert("apple", 10);
insert("banana", 20);
insert("orange", 30);
insert("grape", 40);
printf("apple: %d\n", get("apple"));
printf("banana: %d\n", get("banana"));
// 删除测试
delete("banana");
printf("删除后 banana: %d\n", get("banana"));
// 重新插入
insert("banana", 50);
printf("重新插入后 banana: %d\n", get("banana"));
return 0;
}