#include <stdio.h>
#include <string.h>
#define HASH_TABLE_SIZE 16
typedef struct menu_node {
char name[32];
void (*func)(void);
struct menu_node *next;
} MenuNode;
MenuNode *hash_table[HASH_TABLE_SIZE];
unsigned int hash_func(const char *str) {
unsigned int hash = 5381;
while (*str) {
hash = ((hash << 5) + hash) + (*str++);
}
return hash;
}
void menu_add(const char *name, void (*func)(void)) {
unsigned int hash = hash_func(name) % HASH_TABLE_SIZE;
MenuNode *node = hash_table[hash];
while (node != NULL) {
if (strcmp(node->name, name) == 0) {
// 菜单项已存在,更新函数指针
node->func = func;
return;
}
node = node->next;
}
// 创建新节点
node = (MenuNode *)malloc(sizeof(MenuNode));
strcpy(node->name, name);
node->func = func;
node->next = hash_table[hash];
hash_table[hash] = node;
}
void menu_remove(const char *name) {
unsigned int hash = hash_func(name) % HASH_TABLE_SIZE;
MenuNode *node = hash_table[hash];
MenuNode *prev = NULL;
while (node != NULL) {
if (strcmp(node->name, name) == 0) {
// 找到要删除的节点
if (prev != NULL) {
prev->next = node->next;
} else {
hash_table[hash] = node->next;
}
free(node);
return;
}
prev = node;
node = node->next;
}
}
void menu_run(const char *name) {
unsigned int hash = hash_func(name) % HASH_TABLE_SIZE;
MenuNode *node = hash_table[hash];
while (node != NULL) {
if (strcmp(node->name, name) == 0) {
// 执行对应的菜单项函数
node->func();
return;
}
node = node->next;
}
printf("菜单项不存在!\n");
}
void menu_func1(void) {
printf("执行菜单项1\n");
}
void menu_func2(void) {
printf("执行菜单项2\n");
}
int main() {
// 添加菜单项
menu_add("item1", menu_func1);
menu_add("item2", menu_func2);
// 运行菜单项
menu_run("item1");
menu_run("item2");
// 删除菜单项
menu_remove("item2");
return 0;
}
|