利用单链表实现电话本的模拟程序:定义单链表的数据类型,将头插法和尾插法、插入、删除、查找、修改、计数、逆置、输出等操作
时间: 2023-10-03 15:11:19 浏览: 83
用链表实现的一个电话本小程序
4星 · 用户满意度95%
定义单链表的数据类型:
```
struct ListNode {
string name;
string phone;
ListNode* next;
};
```
头插法:
```
ListNode* head = nullptr;
void insertAtHead(string name, string phone) {
ListNode* node = new ListNode{name, phone, nullptr};
if (head == nullptr) {
head = node;
} else {
node->next = head;
head = node;
}
}
```
尾插法:
```
ListNode* head = nullptr;
void insertAtTail(string name, string phone) {
ListNode* node = new ListNode{name, phone, nullptr};
if (head == nullptr) {
head = node;
} else {
ListNode* tail = head;
while (tail->next != nullptr) {
tail = tail->next;
}
tail->next = node;
}
}
```
插入:
```
void insert(string name, string phone, int index) {
ListNode* node = new ListNode{name, phone, nullptr};
if (index == 0) {
insertAtHead(name, phone);
} else {
ListNode* prev = head;
for (int i = 0; i < index - 1 && prev != nullptr; i++) {
prev = prev->next;
}
if (prev != nullptr) {
node->next = prev->next;
prev->next = node;
}
}
}
```
删除:
```
void remove(string name) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr && curr->name != name) {
prev = curr;
curr = curr->next;
}
if (curr != nullptr) {
if (prev == nullptr) {
head = curr->next;
} else {
prev->next = curr->next;
}
delete curr;
}
}
```
查找:
```
ListNode* find(string name) {
ListNode* curr = head;
while (curr != nullptr && curr->name != name) {
curr = curr->next;
}
return curr;
}
```
修改:
```
void update(string name, string newPhone) {
ListNode* node = find(name);
if (node != nullptr) {
node->phone = newPhone;
}
}
```
计数:
```
int count() {
int cnt = 0;
ListNode* curr = head;
while (curr != nullptr) {
cnt++;
curr = curr->next;
}
return cnt;
}
```
逆置:
```
void reverse() {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}
```
输出:
```
void print() {
ListNode* curr = head;
while (curr != nullptr) {
cout << curr->name << ": " << curr->phone << endl;
curr = curr->next;
}
}
```
阅读全文