#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct Node {
char name[50];
struct Node *next;
} Node;
Node *hashTable[TABLE_SIZE];
unsigned int hash(char *str) {
unsigned int hash = 0;
while (*str) {
hash = (hash << 5) + *str++;
}
return hash % TABLE_SIZE;
}
void initializeHashTable() {
for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = NULL;
}
}
int hasVoted(char *name) {
unsigned int index = hash(name);
Node *current = hashTable[index];
while (current != NULL) {
if (strcmp(current->name, name) == 0) {
return 1;
}
current = current->next;
}
return 0;
}
void vote(char *name) {
if (hasVoted(name)) {
printf("%s 已经投过票了!\n", name);
} else {
unsigned int index = hash(name);
Node *newNode = (Node *)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败\n");
return;
}
strcpy(newNode->name, name);
newNode->next = hashTable[index];
hashTable[index] = newNode;
printf("%s 成功投票!\n", name);
}
}
int main() {
initializeHashTable();
vote("Alice");
vote("Bob");
vote("Alice");
return 0;
}