请使用单链表实现通讯录,每个链表节点包含name、address、phone这3个信息。(1)请写一个create()函数存储3个人的通讯信息; (2)请遍历输出问题(1)创建的通讯录链表;
时间: 2024-05-10 13:15:54 浏览: 83
danlianbiao.rar_VC 链表_单链表 通讯录
以下是使用单链表实现通讯录的代码,其中包含了create()函数和遍历输出通讯录链表的函数display():
```c++
#include <iostream>
using namespace std;
// 定义通讯录节点结构体
struct Person {
string name;
string address;
string phone;
Person* next;
};
// 创建通讯录链表
void create(Person*& head) {
// 创建3个节点
Person* p1 = new Person;
p1->name = "Alice";
p1->address = "123 Main St.";
p1->phone = "555-1234";
p1->next = NULL;
Person* p2 = new Person;
p2->name = "Bob";
p2->address = "456 Elm St.";
p2->phone = "555-5678";
p2->next = NULL;
Person* p3 = new Person;
p3->name = "Charlie";
p3->address = "789 Oak St.";
p3->phone = "555-9012";
p3->next = NULL;
// 将3个节点连接成链表
head = p1;
p1->next = p2;
p2->next = p3;
}
// 遍历输出通讯录链表
void display(Person* head) {
while (head != NULL) {
cout << "Name: " << head->name << endl;
cout << "Address: " << head->address << endl;
cout << "Phone: " << head->phone << endl << endl;
head = head->next;
}
}
int main() {
Person* head = NULL;
create(head);
display(head);
return 0;
}
```
运行结果:
```
Name: Alice
Address: 123 Main St.
Phone: 555-1234
Name: Bob
Address: 456 Elm St.
Phone: 555-5678
Name: Charlie
Address: 789 Oak St.
Phone: 555-9012
```
阅读全文