#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node {
int key;
struct Node* next;
} Node;
typedef struct {
int size;
Node** table;
} HashTable;
HashTable* createHashTable(int size) {
HashTable* hashTable = (HashTable*)malloc(sizeof(HashTable));
hashTable->size = size;
hashTable->table = (Node**)malloc(sizeof(Node*) * size);
for (int i = 0; i < size; i++)
hashTable->table[i] = NULL;
return hashTable;
}
int hashFunction(int key, int size) {
return key % size;
}
void insert(HashTable* hashTable, int key) {
int index = hashFunction(key, hashTable->size);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->next = NULL;
newNode->next = hashTable->table[index];
hashTable->table[index] = newNode;
}
bool hasVoted(HashTable* hashTable, int key) {
int index = hashFunction(key, hashTable->size);
Node* current = hashTable->table[index];
while (current != NULL) {
if (current->key == key)
return true;
current = current->next;
}
return false;
}
int main() {
int votes[] = {1, 2, 3, 1, 2, 4, 5, 3, 6, 7, 1};
int numVotes = sizeof(votes) / sizeof(votes[0]);
HashTable* hashTable = createHashTable(2 * numVotes);
printf("投票结果:\n");
for (int i = 0; i < numVotes; i++) {
int vote = votes[i];
if (!hasVoted(hashTable, vote)) {
printf("投票给 %d\n", vote);
insert(hashTable, vote);
} else {
printf("已经投过票给 %d,不能重复投票\n", vote);
}
}
for (int i = 0; i < hashTable->size; i++) {
Node* current = hashTable->table[i];
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
}
free(hashTable->table);
free(hashTable);
return 0;
}