简单的哈希表链式地址法应用(通讯录/商品价格)

代码如下(首字母分类,用小写字母查询,代码按实际情况修改)

用指针传递数据:

#include<iostream>
#include<string>
#pragma warning(disable:4996)
using namespace std;
typedef struct a {
	char name[20];
	char number[20];
	struct a* next;
}person;//定义一个结构体并命名
void meun() {
	cout << "选择操作:1.添加 2.删除 3.修改 4.查询 5。退出\n";
}//菜单操作
void add(person *tail[]) {
	cout << "添加一位";
	person* p;
	p = new(person);
	cin >> p->name >> p->number;
	tail[p->name[0]-97]->next = p;
	p->next = NULL;
	tail[p->name[0] - 97] = p;
}//添加入表
person* search(person *head[]) {
	cout << "查询一位";
	person* p;
	p = new(person);
	cin >> p->name;
	person *search;
	search = head[p->name[0] - 97];
	while (strcmp(search->name,p->name)!=0) {
		search = search->next;
		if (search == NULL) {
			cout << "暂无此人\n";
			return NULL;//表空未找到,返回NULL
		}
	}
	return search;
}//查询表单
void change(person* head[]) {
	person* p = search(head);
	if (p == NULL) {
		return;
	}
	cout << "1.修改名字 2.修改号码 3.同时修改 4.不修改\n";
	int choice;
	cin >> choice;
	switch (choice) {
	case 1:cin >> p->name;break;
	case 2:cin >> p->number; break;
	case 3:cin >> p->name >> p->number;break;
	default:break;
	}
}//修改数值
void dlete(person* head[]) {
	cout << "输入要删除对象:";
	char pe[20];
	cin >> pe;
	person* search = head[pe[0] - 97];
    if (search->next == NULL) {
	cout << "暂无此人\n";
	return;
}
	while (strcmp(search->next->name, pe) != 0) {
		search = search->next;
        if (search->next == NULL) {
	        cout << "暂无此人\n";
	        return;
        }
	}
	person* p = search->next;
	search->next = p->next;
	free(p);
}//删除元素
int main() {
	person* head[26], * tail[26];
	for (int i = 0; i < 26; i++) {
		head[i] = (person*)malloc(sizeof(person));
		head[i]->next = NULL;
		tail[i]=head[i];
	}
	int choice = 0;
	while (choice!=5) {
		meun();
		cin >> choice;
		switch (choice) {
		case 1:add(tail); break;
		case 2:dlete(head); break;
		case 3:change(head); break;
		case 4:person * p = search(head); if (p == NULL) { break; }cout << p->name << " " << p->number << endl; break;
		}
	}
}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值