帮我写一下这个建立线性链表并完成取值、查找、插入、和删除操作要求在main()函数中应用的代码
时间: 2024-09-25 09:18:03 浏览: 34
创建一个简单的单向线性链表,并在`main()`函数中演示取值、查找、插入和删除操作,我们可以使用C++语言来实现。首先,我们需要定义链表节点结构体和一些基本操作的类成员函数。
```cpp
#include <iostream>
// 定义链表节点结构体
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
// 构造函数
LinkedList() : head(nullptr) {}
// 插入节点
void insert(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// 取值
int get(int index) const {
if (index < 0 || index >= size()) {
throw std::out_of_range("Index out of range");
}
Node* current = head;
for (int i = 0; i < index; ++i) {
current = current->next;
}
return current->data;
}
// 查找
bool find(int value) const {
Node* current = head;
while (current != nullptr) {
if (current->data == value) {
return true;
}
current = current->next;
}
return false;
}
// 删除
void remove(int value) {
if (head == nullptr) {
return;
}
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node* toRemove = current->next;
current->next = current->next->next;
delete toRemove;
}
}
// 返回链表长度
int size() const {
int count = 0;
Node* current = head;
while (current != nullptr) {
++count;
current = current->next;
}
return count;
}
// 主函数展示操作
void demonstrateMain() {
try {
insert(5);
insert(10);
insert(15);
std::cout << "Values: ";
Node* node = head;
while (node != nullptr) {
std::cout << node->data << " -> ";
node = node->next;
}
std::cout << "nullptr\n";
std::cout << "Find 10: " << (find(10) ? "Found" : "Not Found") << "\n";
std::cout << "Get index 1: " << get(1) << "\n";
remove(10);
std::cout << "After removing 10:\n";
node = head;
while (node != nullptr) {
std::cout << node->data << " -> ";
node = node->next;
}
std::cout << "nullptr\n";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
}
}
};
int main() {
LinkedList list;
list.demonstrateMain();
return 0;
}
```
在这个示例中,我们在`LinkedList`类中实现了插入、取值、查找和删除功能。在`main()`函数中,我们创建了一个链表实例并展示了如何使用这些方法。注意这只是一个基础的实现,实际使用时可能需要考虑异常处理和其他细节。
阅读全文