编辑代码

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