#include #include #include #define TAILLE_TABLE 10 // Structure pour stocker les données d'une personne typedef struct Personne { int id; char nom[50]; struct Personne* suivant; // Pour le chaînage en cas de collision } Personne; // Table de hachage Personne* tableHachage[TAILLE_TABLE] = {NULL}; // Fonction de hachage simple (somme des chiffres de l'identifiant) int fonctionHachage(int id) { int somme = 0; while (id > 0) { somme += id % 10; id /= 10; } return somme % TAILLE_TABLE; } // Fonction pour ajouter une personne à la table de hachage void insererPersonne(int id, const char* nom) { Personne* nouvellePersonne = (Personne*)malloc(sizeof(Personne)); if (nouvellePersonne == NULL) { perror("Allocation mémoire échouée"); exit(EXIT_FAILURE); } nouvellePersonne->id = id; strcpy(nouvellePersonne->nom, nom); nouvellePersonne->suivant = NULL; int index = fonctionHachage(id); // Gestion des collisions par chaînage if (tableHachage[index] == NULL) { tableHachage[index] = nouvellePersonne; } else { Personne* courant = tableHachage[index]; while (courant->suivant != NULL) { courant = courant->suivant; } courant->suivant = nouvellePersonne; } } // Fonction pour rechercher une personne par son identifiant Personne* trouverPersonne(int id) { int index = fonctionHachage(id); Personne* courant = tableHachage[index]; while (courant != NULL) { if (courant->id == id) { return courant; } courant = courant->suivant; } return NULL; // Personne non trouvée } // Fonction pour afficher la table de hachage void afficherTableHachage() { for (int i = 0; i < TAILLE_TABLE; i++) { printf("[%d] -> ", i); Personne* courant = tableHachage[i]; while (courant != NULL) { printf("(%d, %s) -> ", courant->id, courant->nom); courant = courant->suivant; } printf("NULL\n"); } } int main() { // Lecture des données depuis un fichier (exemple.txt) FILE* fichier = fopen("personnes.txt", "r"); if (fichier == NULL) { perror("Erreur lors de l'ouverture du fichier"); return EXIT_FAILURE; } int id; char nom[50]; while (fscanf(fichier, "%d %s", &id, nom) == 2) { insererPersonne(id, nom); } fclose(fichier); // Affichage de la table de hachage afficherTableHachage(); // Recherche d'une personne par son identifiant int idRecherche; printf("\nEntrez l'identifiant à rechercher : "); scanf("%d", &idRecherche); Personne* resultat = trouverPersonne(idRecherche); if (resultat != NULL) { printf("Personne trouvée : (%d, %s)\n", resultat->id, resultat->nom); } else { printf("Personne non trouvée.\n"); } return EXIT_SUCCESS; }