代码如下(首字母分类,用小写字母查询,代码按实际情况修改)
用指针传递数据:
#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;
}
}
}