编辑代码

#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};

    // 假设有5个选项,每个选项的编号为1到5
    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}; // 假设有9个投票者
    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;
}