以下是使用C语言编写的一个简单的哈希表查找程序的示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TABLE_SIZE 10 // 哈希表大小
#define R 3 // 平均查找长度

typedef struct {
    char name[20];
    int id;
} Person;

typedef struct {
    Person* data;
    int size;
} HashTable;

int hash(char* name) {
    int sum = 0;
    for (int i = 0; i < strlen(name); i++) {
        sum += name[i];
    }
    return sum % TABLE_SIZE;
}

void insert(HashTable* table, Person person) {
    int index = hash(person.name);
    while (table->data[index].id != -1) {
        index = (index + 1) % TABLE_SIZE; // 线性探测法解决冲突
    }
    table->data[index] = person;
    table->size++;
}

int search(HashTable* table, char* name) {
    int index = hash(name);
    int count = 0;
    while (table->data[index].id != -1) {
        if (strcmp(table->data[index].name, name) == 0) {
            return index;
        }
        index = (index + 1) % TABLE_SIZE;
        count++;
        if (count > R) {
            return -1; // 超过平均查找长度,返回-1表示未找到
        }
    }
    return -1; // 未找到
}

int main() {
    HashTable table;
    table.size = 0;
    table.data = (Person*)malloc(sizeof(Person) * TABLE_SIZE);
    for (int i = 0; i < TABLE_SIZE; i++) {
        table.data[i].id = -1; // 初始化哈希表
    }

    // 添加一些人名到哈希表中
    insert(&table, (Person){"Alice", 1});
    insert(&table, (Person){"Bob", 2});
    insert(&table, (Person){"Charlie", 3});
    insert(&table, (Person){"David", 4});
    insert(&table, (Person){"Eve", 5});

    // 在哈希表中查找指定人名
    char name[20];
    printf("请输入要查找的人名:");
    scanf("%s", name);
    int index = search(&table, name);
    if (index != -1) {
        printf("找到了,该人的id是:%d\n", table.data[index].id);
    } else {
        printf("未找到该人\n");
    }

    free(table.data);
    return 0;
}

这个程序使用了线性探测法解决哈希冲突,即如果哈希表中的某个位置已经被占用,则继续往后查找下一个空位置。当查找次数超过平均查找长度R时,认为未找到。你可以根据实际需求修改哈希表的大小和平均查找长度的值

用C语言编写可运行的代码实现以下功能三、哈希表查找针对某个集体比如你所在的班级中的人名设计一个哈希表使得平均查找长度不超过R完成相应的建表和查找程序。1、	分析问题;2、	创建此问题的哈希表;3、	指定一个人名在哈希表中进行查找并输出查找结果;

原文地址: https://www.cveoy.top/t/topic/hBDq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录