c++双向链表实现通讯录
时间: 2023-08-27 16:05:11 浏览: 160
以下是使用 C++ 实现双向链表的通讯录的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义联系人结构体
struct Contact {
string name;
string phone;
};
// 定义双向链表节点结构体
struct ListNode {
Contact data;
ListNode* prev;
ListNode* next;
ListNode(Contact value): data(value), prev(nullptr), next(nullptr) {}
};
// 定义双向链表类
class DoubleLinkedList {
private:
ListNode* head;
ListNode* tail;
int size;
public:
DoubleLinkedList(): head(nullptr), tail(nullptr), size(0) {}
~DoubleLinkedList() {
ListNode* p = head;
while (p != nullptr) {
ListNode* q = p->next;
delete p;
p = q;
}
head = tail = nullptr;
size = 0;
}
void append(Contact value) {
ListNode* node = new ListNode(value);
if (tail == nullptr) {
head = tail = node;
} else {
tail->next = node;
node->prev = tail;
tail = node;
}
size++;
}
void remove(ListNode* node) {
if (node == nullptr) return;
if (node == head) {
head = head->next;
if (head != nullptr) {
head->prev = nullptr;
} else {
tail = nullptr;
}
} else if (node == tail) {
tail = tail->prev;
if (tail != nullptr) {
tail->next = nullptr;
} else {
head = nullptr;
}
} else {
node->prev->next = node->next;
node->next->prev = node->prev;
}
delete node;
size--;
}
void print() {
ListNode* p = head;
while (p != nullptr) {
cout << "Name: " << p->data.name << ", Phone: " << p->data.phone << endl;
p = p->next;
}
}
int getSize() {
return size;
}
};
int main() {
DoubleLinkedList contacts;
Contact c1 = {"Alice", "123456789"};
Contact c2 = {"Bob", "234567890"};
Contact c3 = {"Charlie", "345678901"};
contacts.append(c1);
contacts.append(c2);
contacts.append(c3);
contacts.print();
cout << "Size: " << contacts.getSize() << endl;
// 删除 Bob 的联系方式
ListNode* p = contacts.head;
while (p != nullptr) {
if (p->data.name == "Bob") {
contacts.remove(p);
break;
}
p = p->next;
}
contacts.print();
cout << "Size: " << contacts.getSize() << endl;
return 0;
}
```
上述代码实现了一个基本的双向链表类,其中节点结构体 `ListNode` 包括了联系人结构体 `Contact` 和前驱节点和后继节点指针。在主函数中,我们创建了三个联系人并添加到双向链表中,然后打印出链表中所有联系人的信息。接着,我们使用循环遍历链表,找到名字为 Bob 的联系人并删除它,最后再次打印出链表中剩余的联系人信息和链表大小。
阅读全文