问题描述:针对某个单位电话号码簿,设计一个哈希表,并完成相应的建表和查表程序。 基本要求:设每个记录有下列数据项:电话号码、用户名、住址。从键盘输入各记录,以用户名为关键字建立哈希表,哈希函数用除留取余数法构造,采用线性探测法解决冲突。可以插入、查找、删除并显示给定用户名的记录,并计算查找长度, 哈希表保存到文件中。 测试数据:取某个单位电话号码簿中的30 个记录。用C语言实现
时间: 2024-02-01 11:16:26 浏览: 54
哈希表的设计与实现(以电话号码查找系统为实例)
3星 · 编辑精心推荐
以下是基于题目要求设计的哈希表的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RECORDS 30
#define TABLE_SIZE 50
struct record {
char phone[12];
char name[20];
char address[50];
};
struct hash_table {
struct record* table[TABLE_SIZE];
int count;
};
unsigned int hash(char* str) {
unsigned int hash = 0;
int c;
while ((c = *str++)) {
hash = hash * 33 + c;
}
return hash % TABLE_SIZE;
}
void insert(struct hash_table* ht, struct record* r) {
if (ht->count >= TABLE_SIZE) {
printf("Error: Hash table is full\n");
return;
}
int index = hash(r->name);
while (ht->table[index] != NULL) {
index = (index + 1) % TABLE_SIZE;
}
ht->table[index] = r;
ht->count++;
}
struct record* search(struct hash_table* ht, char* name, int* length) {
int index = hash(name);
int i = 0;
while (ht->table[index] != NULL && strcmp(ht->table[index]->name, name) != 0) {
index = (index + 1) % TABLE_SIZE;
i++;
}
*length = i;
return ht->table[index];
}
void delete(struct hash_table* ht, char* name) {
int index = hash(name);
while (ht->table[index] != NULL) {
if (strcmp(ht->table[index]->name, name) == 0) {
ht->table[index] = NULL;
ht->count--;
return;
}
index = (index + 1) % TABLE_SIZE;
}
}
void display(struct hash_table* ht) {
for (int i = 0; i < TABLE_SIZE; i++) {
if (ht->table[i] != NULL) {
printf("%s %s %s\n", ht->table[i]->phone, ht->table[i]->name, ht->table[i]->address);
}
}
}
void save_table(struct hash_table* ht) {
FILE* file = fopen("hash_table.dat", "wb");
fwrite(ht->table, sizeof(struct record*), TABLE_SIZE, file);
fclose(file);
}
void load_table(struct hash_table* ht) {
FILE* file = fopen("hash_table.dat", "rb");
fread(ht->table, sizeof(struct record*), TABLE_SIZE, file);
fclose(file);
}
int main() {
struct hash_table ht = { { 0 }, 0 };
// Insert records
for (int i = 0; i < MAX_RECORDS; i++) {
struct record* r = malloc(sizeof(struct record));
printf("Enter phone number, name, and address: ");
scanf("%s %s %[^\n]", r->phone, r->name, r->address);
insert(&ht, r);
}
// Save hash table to file
save_table(&ht);
// Load hash table from file
load_table(&ht);
// Search for record
char name[20];
printf("Enter name to search: ");
scanf("%s", name);
int length;
struct record* r = search(&ht, name, &length);
if (r != NULL) {
printf("%s %s %s\n", r->phone, r->name, r->address);
printf("Search length: %d\n", length);
} else {
printf("Record not found\n");
}
// Delete record
printf("Enter name to delete: ");
scanf("%s", name);
delete(&ht, name);
// Display hash table
display(&ht);
return 0;
}
```
该程序使用了除留取余数法作为哈希函数,并采用线性探测法解决冲突。通过 `insert` 函数将记录插入哈希表中,通过 `search` 函数查找指定用户名的记录并计算查找长度,通过 `delete` 函数删除指定用户名的记录,通过 `display` 函数显示哈希表中所有记录。此外,通过 `save_table` 函数将哈希表保存到文件中,通过 `load_table` 函数从文件中加载哈希表。
阅读全文