请编写链表的Init、Length、GetElem、Locate、Insert、Delete和CreatList(头插或尾插)七个函数,并编写main函数调用以上函数实现完整的功能。请统一提交一个cpp文件。
时间: 2024-09-22 22:06:43 浏览: 36
头插法、尾插法、链表长度test-c-master.zip
在C++中,我们可以创建一个简单的单向链表结构并为其编写上述七个基本操作的函数。这里是一个简化的示例:
```cpp
#include <iostream>
// 定义链表节点结构
struct Node {
int data;
Node* next;
};
// 初始化链表为空
Node* Init() {
return nullptr;
}
// 计算链表长度
int Length(Node* head) {
int length = 0;
if (head != nullptr) {
Node* current = head;
while (current != nullptr) {
length++;
current = current->next;
}
}
return length;
}
// 获取指定位置的元素
int GetElem(Node* head, int index) {
if (index >= 0 && index < Length(head)) {
Node* current = head;
for (int i = 0; i < index; i++) {
current = current->next;
}
return current->data;
} else {
throw std::out_of_range("Index out of range");
}
}
// 查找特定元素的位置
int Locate(Node* head, int value) {
Node* current = head;
for (int i = 0; current != nullptr && current->data != value; i++, current = current->next) {}
if (current == nullptr) return -1; // 未找到返回-1
return i;
}
// 在指定位置插入新元素
void Insert(Node*& head, int index, int value) {
if (index <= 0 || index > Length(head)) {
throw std::out_of_range("Invalid index");
}
Node* newNode = new Node{value};
if (index == 0) { // 头插
newNode->next = head;
head = newNode;
} else {
Node* prev = head;
for (int i = 0; i < index - 1; i++) {
prev = prev->next;
}
newNode->next = prev->next;
prev->next = newNode;
}
}
// 删除指定位置的元素
void Delete(Node*& head, int index) {
if (index < 0 || index >= Length(head)) {
throw std::out_of_range("Invalid index");
}
if (index == 0) { // 头部删除
Node* temp = head;
head = head->next;
delete temp;
} else {
Node* current = head;
for (int i = 0; i < index - 1; i++) {
current = current->next;
}
Node* prev = current->next;
prev->next = prev->next->next;
delete current->next;
}
}
// 创建一个空列表
Node* CreatList(int size = 0) {
if (size > 0) {
Node* head = new Node{0}; // 假设大小为0时创建一个空节点作为头结点
for (int i = 1; i < size; i++) {
Insert(head, i, i); // 尾插
}
return head;
} else {
return Init();
}
}
// 主函数演示链表的操作
int main() {
Node* list = CreatList(5);
std::cout << "Length: " << Length(list) << std::endl;
std::cout << "Element at index 2: " << GetElem(list, 2) << std::endl;
try {
int position = Locate(list, 3);
if (position != -1) {
std::cout << "Found element at position: " << position << std::endl;
} else {
std::cout << "Element not found." << std::endl;
}
Insert(list, 4, 99);
std::cout << "After inserting at position 4: ";
for (int i = 0; list != nullptr; i++, list = list->next)
std::cout << list->data << " ";
Delete(list, 2);
std::cout << "\nAfter deleting at position 2: ";
for (int i = 0; list != nullptr; i++, list = list->next)
std::cout << list->data << " ";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
delete list; // 清理内存
return 0;
}
```
这个例子展示了如何在C++中创建一个简单的单向链表以及提供基本的初始化、查找、插入和删除操作。在`main`函数中,我们对链表进行了各种操作以便展示其功能。
阅读全文