请使用单链表实现通讯录,每个链表节点包含name、address、phone这3个信息。 (1)请写一个create()函数存储3个人的通讯信息
时间: 2024-06-08 12:11:48 浏览: 87
好的,这里给出使用C++语言实现单链表存储通讯录的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 定义通讯录结构体
struct Contact {
string name;
string address;
string phone;
Contact *next;
};
// 创建一个通讯录节点
Contact* createContact(string name, string address, string phone) {
Contact *p = new Contact;
p->name = name;
p->address = address;
p->phone = phone;
p->next = nullptr;
return p;
}
// 创建通讯录链表
Contact* create() {
Contact *head = nullptr, *tail = nullptr;
for (int i = 0; i < 3; i++) {
string name, address, phone;
cout << "请输入第" << i+1 << "个人的信息" << endl;
cout << "姓名:";
cin >> name;
cout << "地址:";
cin >> address;
cout << "电话:";
cin >> phone;
Contact *p = createContact(name, address, phone);
if (head == nullptr) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
// 输出通讯录链表
void print(Contact *head) {
cout << "通讯录:" << endl;
Contact *p = head;
while (p) {
cout << "姓名:" << p->name;
cout << " 地址:" << p->address;
cout << " 电话:" << p->phone << endl;
p = p->next;
}
}
int main() {
Contact *head = create();
print(head);
return 0;
}
```
运行结果:
```
请输入第1个人的信息
姓名:张三
地址:北京
电话:12345678901
请输入第2个人的信息
姓名:李四
地址:上海
电话:12345678902
请输入第3个人的信息
姓名:王五
地址:广州
电话:12345678903
通讯录:
姓名:张三 地址:北京 电话:12345678901
姓名:李四 地址:上海 电话:12345678902
姓名:王五 地址:广州 电话:12345678903
```
阅读全文
相关推荐















