#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define TABLE_SIZE 100
typedef struct Node {
int key;
bool voted;
struct Node* next;
} Node;
Node* createNode(int key) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->voted = false;
newNode->next = NULL;
return newNode;
}
int hashFunction(int key) {
return key % TABLE_SIZE;
}
void insertNode(Node* hashTable[], int key) {
int index = hashFunction(key);
Node* newNode = createNode(key);
if (hashTable[index] == NULL) {
hashTable[index] = newNode;
} else {
Node* current = hashTable[index];
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
bool searchNode(Node* hashTable[], int key) {
int index = hashFunction(key);
Node* current = hashTable[index];
while (current != NULL) {
if (current->key == key) {
if (current->voted) {
return true;
} else {
current->voted = true;
return false;
}
}
current = current->next;
}
return false;
}
int main() {
Node* hashTable[TABLE_SIZE] = {NULL};
int options[] = {1, 2, 3, 4, 5};
int numOptions = sizeof(options) / sizeof(options[0]);
int voters[] = {1, 2, 3, 4, 5, 4, 3, 2, 1};
int numVoters = sizeof(voters) / sizeof(voters[0]);
for (int i = 0; i < numVoters; i++) {
int option = voters[i];
if (searchNode(hashTable, option)) {
printf("选项 %d 已经被投过票\n", option);
} else {
insertNode(hashTable, option);
printf("投票者 %d 投票给选项 %d\n", i + 1, option);
}
}
return 0;
}