建立一个通讯录单链表,包含姓名,地址,邮编,电话,编程实现链表插入,删除和显示,c++
时间: 2024-06-13 19:08:43 浏览: 185
以下是建立通讯录单链表,包含姓名、地址、邮编、电话的C++代码实现,其中包括链表的插入、删除和显示功能:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
// 定义通讯录结构体
struct Contact {
char name[20];
char address[50];
char postcode[10];
char phone[20];
Contact* next;
};
// 初始化头结点
Contact* init() {
Contact* head = new Contact;
head->next = NULL;
return head;
}
// 插入结点
void insert(Contact* head, Contact* node) {
Contact* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
node->next = NULL;
}
// 删除结点
void remove(Contact* head, char* name) {
Contact* p = head;
while (p->next != NULL) {
if (strcmp(p->next->name, name) == 0) {
Contact* q = p->next;
p->next = q->next;
delete q;
return; }
p = p->next;
}
cout << "未找到该联系人!" << endl;
}
// 显示通讯录
void display(Contact* head) {
Contact* p = head->next;
while (p != NULL) {
cout << "姓名:" << p->name << endl;
cout << "地址:" << p->address << endl;
cout << "邮编:" << p->postcode << endl;
cout << "电话:" << p->phone << endl;
cout << endl;
p = p->next;
}
}
int main() {
Contact* head = init();
int choice;
while (true) {
cout << "请选择操作:" << endl;
cout << "1. 插入联系人" << endl;
cout << "2. 删除联系人" << endl;
cout << "3. 显示通讯录" << endl;
cout << "4. 退出程序" << endl;
cin >> choice;
switch (choice) {
case 1: {
Contact* node = new Contact;
cout << "请输入联系人姓名:";
cin >> node->name;
cout << "请输入联系人地址:";
cin >> node->address;
cout << "请输入联系人邮编:";
cin >> node->postcode;
cout << "请输入联系人电话:";
cin >> node->phone;
insert(head, node);
cout << "联系人添加成功!" << endl;
break;
}
case 2: {
char name[20];
cout << "请输入要删除的联系人姓名:";
cin >> name;
remove(head, name);
break;
}
case 3: {
display(head);
break;
}
case 4: {
return 0;
}
default: {
cout << "输入有误,请重新输入!" << endl;
break;
}
}
}
return 0;
}
```
阅读全文