#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct {
int voter_id;
char candidate[50];
} Vote;
typedef struct {
int is_occupied;
Vote vote;
} HashEntry;
typedef struct {
HashEntry entries[TABLE_SIZE];
} HashTable;
void initializeHashTable(HashTable *hashTable) {
for (int i = 0; i < TABLE_SIZE; ++i) {
hashTable->entries[i].is_occupied = 0;
}
}
int hashFunction(int voter_id) {
return voter_id % TABLE_SIZE;
}
int vote(HashTable *hashTable, int voter_id, const char *candidate) {
int index = hashFunction(voter_id);
while (hashTable->entries[index].is_occupied) {
if (hashTable->entries[index].vote.voter_id == voter_id) {
printf("投票者%d:已经投过票了\n", voter_id);
return 0;
}
index = (index + 1) % TABLE_SIZE;
}
hashTable->entries[index].is_occupied = 1;
hashTable->entries[index].vote.voter_id = voter_id;
strncpy(hashTable->entries[index].vote.candidate, candidate, sizeof(hashTable->entries[index].vote.candidate));
printf("投票者%d:投给了%s\n", voter_id, candidate);
return 1;
}
void getVoteResult(HashTable *hashTable) {
printf("\n投票结果:\n");
for (int i = 0; i < TABLE_SIZE; ++i) {
if (hashTable->entries[i].is_occupied) {
printf("投票者%d: 投给了%s\n", hashTable->entries[i].vote.voter_id, hashTable->entries[i].vote.candidate);
}
}
}
int main() {
HashTable hashTable;
initializeHashTable(&hashTable);
vote(&hashTable, 1, "参选者A");
vote(&hashTable, 3, "参选者B");
vote(&hashTable, 1, "参选者C");
vote(&hashTable, 4, "参选者A");
getVoteResult(&hashTable);
return 0;
}