c语言哈希表电话号码查询系统源代码
时间: 2023-08-03 08:07:00 浏览: 119
哈希表实现电话号码查询系统
以下是一个简单的基于哈希表实现的电话号码查询系统的C语言源代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct node {
char name[20];
char phone[20];
struct node *next;
} Node;
Node *table[TABLE_SIZE];
unsigned int hash(char *str) {
unsigned int hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c;
return hash % TABLE_SIZE;
}
Node *find(char *name) {
unsigned int index = hash(name);
Node *p;
for (p = table[index]; p != NULL; p = p->next)
if (strcmp(name, p->name) == 0)
return p;
return NULL;
}
void insert(char *name, char *phone) {
unsigned int index = hash(name);
Node *p;
for (p = table[index]; p != NULL; p = p->next)
if (strcmp(name, p->name) == 0) {
strcpy(p->phone, phone);
return;
}
p = (Node *) malloc(sizeof(Node));
strcpy(p->name, name);
strcpy(p->phone, phone);
p->next = table[index];
table[index] = p;
}
void delete(char *name) {
unsigned int index = hash(name);
Node *p, *q;
for (q = NULL, p = table[index]; p != NULL; q = p, p = p->next)
if (strcmp(name, p->name) == 0) {
if (q == NULL)
table[index] = p->next;
else
q->next = p->next;
free(p);
return;
}
}
void display() {
int i;
Node *p;
for (i = 0; i < TABLE_SIZE; ++i)
for (p = table[i]; p != NULL; p = p->next)
printf("%s\t%s\n", p->name, p->phone);
}
int main() {
char name[20], phone[20];
int choice;
while (1) {
printf("\nTelephone directory\n");
printf("1. Find\n2. Insert\n3. Delete\n4. Display\n5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter name: ");
scanf("%s", name);
Node *p = find(name);
if (p)
printf("%s\t%s\n", p->name, p->phone);
else
printf("Name not found\n");
break;
case 2:
printf("Enter name: ");
scanf("%s", name);
printf("Enter phone number: ");
scanf("%s", phone);
insert(name, phone);
break;
case 3:
printf("Enter name: ");
scanf("%s", name);
delete(name);
break;
case 4:
display();
break;
case 5:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}
```
该程序使用了一个大小为100的哈希表来存储电话号码。它实现了四个基本操作:查找、插入、删除和显示。在运行程序时,用户可以选择要执行的操作。如果选择插入操作,则需要输入姓名和电话号码。如果选择查找操作,则需要输入姓名,程序将输出该姓名对应的电话号码。如果选择删除操作,则需要输入姓名,程序将从哈希表中删除该用户的信息。如果选择显示操作,则程序将输出哈希表中所有用户的姓名和电话号码。
阅读全文