将代码整合到一起,并用常用的函数写代码
时间: 2024-10-20 14:06:43 浏览: 24
下面是将上述功能整合在一起,使用常用函数的形式编写的完整示例代码:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
// 定义链表节点结构
struct Node {
int value;
Node* next;
};
// 创建链表
void createList(Node*& head) {
srand(time(0));
for (int i = 0; i < 10; ++i) {
int num = rand() % 90 + 10;
Node* newNode = new Node{num, nullptr};
if (head == nullptr) {
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
}
// 遍历链表
void traverseList(Node* head) {
printList(head);
}
// 打印链表
void printList(Node* node) {
while (node != nullptr) {
std::cout << node->value << " -> ";
node = node->next;
}
std::cout << "NULL" << std::endl;
}
// 查找元素
bool searchElement(Node* head, int target) {
return findElement(head, target);
}
// 查找元素并返回结果
bool findElement(Node* head, int target) {
Node* current = head;
while (current != nullptr) {
if (current->value == target) {
std::cout << "找到了元素 " << target << std::endl;
return true;
}
current = current->next;
}
std::cout << "未找到元素 " << target << std::endl;
return false;
}
// 插入元素
void insertElement(Node*& head, int value, int position) {
if (position <= 0) {
std::cout << "插入位置无效" << std::endl;
return;
}
insertAtPosition(head, value, position);
}
// 在特定位置插入元素
void insertAtPosition(Node*& head, int value, int position) {
Node* newNode = new Node{value, nullptr};
Node* prev = nullptr;
Node* current = head;
for (int i = 0; i < position - 1 && current != nullptr; ++i) {
prev = current;
current = current->next;
}
if (prev == nullptr) {
newNode->next = head;
head = newNode;
} else {
newNode->next = current;
prev->next = newNode;
}
}
// 删除元素
void deleteElement(Node*& head, int target) {
if (deleteElementRecursive(head, target)) {
std::cout << "元素 " << target << " 已经被删除" << std::endl;
} else {
std::cout << "无法找到要删除的元素 " << target << std::endl;
}
}
// 递归删除元素
bool deleteElementRecursive(Node*& head, int target) {
if (head == nullptr) {
return false;
}
if (head->value == target) {
Node* temp = head;
head = head->next;
delete temp;
return true;
} else {
bool found = deleteElementRecursive(head->next, target);
if (found) {
return true;
}
}
return false;
}
int main() {
Node* listHead = nullptr;
createList(listHead); // 创建链表
traverseList(listHead); // 遍历链表
int target = 50; // 示例查找值
if (searchElement(listHead, target)) {
std::cout << "尝试插入元素 75 到位置 3" << std::endl;
insertElement(listHead, 75, 3); // 插入元素
traverseList(listHead); // 更新遍历
} else {
std::cout << "查找失败" << std::endl;
}
deleteElement(listHead, 50); // 删除元素
return 0;
}
```
阅读全文