数据结构的作业,先放在这,以后有空就看一下。
- 查找&删除:按姓名,分别进入对应程序,查找到的信息单行显示,删除失败不进行任何改变。
- 插入:输入需要插入的人数和分别的姓名和电话号码来进行插入,人数超过初始化开辟的空间时,申请另一片空间,姓名重复时,提示重新输入。
- 显示:界面显示最新的联系人信息以及联系人数量。
- 销毁:退出时先销毁通讯录。
#include
#include
#define DEFAULTLENGTH 15
using namespace std;
typedef struct People {
string name; //联系人姓名
string number; //联系人号码
}People;
typedef struct PhoneList {
People* data;
int maxlength;
int length;
}PhoneList;
int initPList(PhoneList& PL) {
PL.data = new People[DEFAULTLENGTH];
PL.maxlength = DEFAULTLENGTH;
PL.length = 0;
return 0;
}
int insertOne(PhoneList& PL, People a) {
if (PL.length == (int)(PL.maxlength * 0.7)) {
People* newP = new People[PL.maxlength = PL.maxlength + DEFAULTLENGTH];
People* old = PL.data;
for (int i = 0; i < PL.length; i++) {
newP[i] = old[i];
}
PL.data = newP;
delete[] old;
}
PL.data[PL.length++] = a;
return 0;
}
int deleteOne(PhoneList& PL) {
cout << "输入要删除的联系人姓名:";
string dname;
cin >> dname;
for (int i = 0; i < PL.length; i++) {
if (PL.data[i].name == dname) {
for (int j = i; j < PL.length; j++) {
PL.data[j] = PL.data[j + 1];
}
PL.length--;
return 0;
}
}
return -1;
}
People* select(PhoneList& PL, string sname) {
for (int i = 0; i < PL.length; i++) {
if (PL.data[i].name == sname) {
return &PL.data[i];
}
}
return NULL;
}
void menu(PhoneList p) {
system("cls");
cout << "n 1.插入 2.删除 3.查找 4.退出 " << endl;
if (p.length == 0) {
cout << "n 当前通讯录为空" << endl;
}
else {
cout << "n 姓名t电话号码" << endl;
}
for (int i = 0; i < p.length; i++)
cout << " " << p.data[i].name << "t" << p.data[i].number << endl;
cout << "ttt人数: " << p.length << endl;
}
void menu(People* p) {
system("cls");
cout << "n 1.插入 2.删除 3.查找 4.退出 " << endl;
if (p == NULL) {
cout << "n 空 " << endl;
}
else {
cout << "n 姓名t电话号码" << endl;
cout << " " << p->name << "t" << p->number << endl;
}
}
int insert(PhoneList& PL) {
int a;
People* s;
cout << "输入需要插入的人数:";
cin >> a;
for (int i = 0; i < a; i++) {
s = new People;
cout << "姓名:";
cin >> s->name;
if (select(PL, s->name)) {
cout << "姓名重复 继续" << endl;
delete s;
continue;
}
cout << "号码:";
cin >> s->number;
insertOne(PL, *s);
}
return 0;
}
int main(int argc, char** argv) {
PhoneList* PL = new PhoneList;
initPList(*PL);
menu(*PL);
int option;
while (1) {
cout << "n选择:";
cin >> option;
switch (option) {
case 1: {
insert(*PL);
menu(*PL);
break;
}case 2: {
deleteOne(*PL);
menu(*PL);
break;
}case 3: {
cout << "输入需要查找的联系人姓名:";
string sname;
cin >> sname;
menu(select(*PL, sname));
break;
}case 4: {
delete [](PL->data);
delete PL;
exit(0);
}
}
}
return 0;
}