c++用单链表实现通讯录
时间: 2024-03-07 16:47:15 浏览: 83
好的,我可以为您提供一个基本的单链表通讯录的实现。首先,我们需要定义一个通讯录的节点结构体,包含姓名、电话号码、邮箱等信息:
```c++
struct Contact {
std::string name;
std::string phone;
std::string email;
Contact* next;
};
```
其中,`next`指向下一个节点。接下来,我们需要定义一个用于管理通讯录的类 `ContactList`,其中包括添加、删除、查找联系人等方法:
```c++
class ContactList {
public:
ContactList() {
head = nullptr;
}
~ContactList() {
Contact* current = head;
while (current != nullptr) {
Contact* next = current->next;
delete current;
current = next;
}
}
void addContact(const std::string& name, const std::string& phone, const std::string& email) {
Contact* newContact = new Contact();
newContact->name = name;
newContact->phone = phone;
newContact->email = email;
newContact->next = head;
head = newContact;
}
void removeContact(const std::string& name) {
Contact* current = head;
Contact* previous = nullptr;
while (current != nullptr) {
if (current->name == name) {
if (previous == nullptr) {
head = current->next;
} else {
previous->next = current->next;
}
delete current;
return;
}
previous = current;
current = current->next;
}
}
Contact* findContact(const std::string& name) {
Contact* current = head;
while (current != nullptr) {
if (current->name == name) {
return current;
}
current = current->next;
}
return nullptr;
}
private:
Contact* head;
};
```
上述代码中,`addContact`方法在链表头部插入一个新的节点,`removeContact`方法删除指定姓名的节点,`findContact`方法查找指定姓名的节点。
使用示例:
```c++
ContactList myContacts;
myContacts.addContact("Alice", "123456", "alice@example.com");
myContacts.addContact("Bob", "789012", "bob@example.com");
myContacts.addContact("Charlie", "345678", "charlie@example.com");
Contact* contact = myContacts.findContact("Bob");
if (contact != nullptr) {
std::cout << "Phone: " << contact->phone << std::endl;
}
myContacts.removeContact("Charlie");
```
以上是一个基本的单链表通讯录实现,您可以根据需要进行扩展和修改。
阅读全文