#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct {
char name[50];
int voted;
} Voter;
typedef struct {
char* key;
Voter* voter;
} Node;
Node* hashTable[TABLE_SIZE];
void initializeHashTable() {
for (int i = 0; i < TABLE_SIZE; ++i) {
hashTable[i] = NULL;
}
}
int hashFunction(char* key) {
int hash = 0;
while (*key) {
hash += *key;
++key;
}
return hash % TABLE_SIZE;
}
int searchVoter(char* name) {
int index = hashFunction(name);
while (hashTable[index] != NULL) {
if (strcmp(hashTable[index]->key, name) == 0) {
return 1;
}
index = (index + 1) % TABLE_SIZE;
}
return 0;
}
void insertVoter(char* name) {
int index = hashFunction(name);
while (hashTable[index] != NULL) {
index = (index + 1) % TABLE_SIZE;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = strdup(name);
newNode->voter = (Voter*)malloc(sizeof(Voter));
strcpy(newNode->voter->name, name);
newNode->voter->voted = 1;
hashTable[index] = newNode;
}
void freeHashTable() {
for (int i = 0; i < TABLE_SIZE; ++i) {
if (hashTable[i] != NULL) {
free(hashTable[i]->key);
free(hashTable[i]->voter);
free(hashTable[i]);
}
}
}
int main() {
initializeHashTable();
char names[][50] = {"Alice", "Bob", "Charlie", "Alice", "David", "Bob"};
int numVoters = sizeof(names) / sizeof(names[0]);
for (int i = 0; i < numVoters; ++i) {
char* voterName = names[i];
if (searchVoter(voterName) == 0) {
printf("%s投票成功!\n", voterName);
insertVoter(voterName);
} else {
printf("%s已经投过票,不能重复投票。\n", voterName);
}
}
freeHashTable();
return 0;
}