基于带头结点的链式存储结构,编写程序,实现下述功能: 1、初始化一个空链表 2、链表的置空和销毁 3、实现元素的查找、插入和删除 4、输出链表的全部元素
时间: 2024-10-19 12:15:29 浏览: 62
基于带头结点的链式存储结构,我们可以创建一个单向链表来实现上述功能。这里是一个简单的C++示例:
```cpp
#include <iostream>
// 定义链表节点
struct ListNode {
int data;
ListNode* next;
ListNode(int val) : data(val), next(nullptr) {}
};
// 初始化一个空链表
ListNode* createEmptyList() {
return new ListNode(0); // 使用0表示头结点,实际数据从第一个节点开始
}
// 置空链表并销毁
void destroyList(ListNode*& head) {
if (head != nullptr) {
ListNode* temp = head;
while (temp != nullptr) {
ListNode* nextTemp = temp->next;
delete temp;
temp = nextTemp;
}
head = nullptr;
}
}
// 元素查找
bool searchElement(const ListNode* head, int target) {
ListNode* curr = head;
while (curr != nullptr) {
if (curr->data == target)
return true;
curr = curr->next;
}
return false;
}
// 插入元素
void insertElement(ListNode*& head, int value, int position = 0) {
if (position == 0) {
ListNode* newNode = new ListNode(value);
newNode->next = head;
head = newNode;
} else {
ListNode* prev = head;
for (int i = 1; i < position && prev != nullptr; ++i)
prev = prev->next;
if (prev == nullptr)
std::cout << "插入位置无效\n";
else {
ListNode* newNode = new ListNode(value);
newNode->next = prev->next;
prev->next = newNode;
}
}
}
// 删除元素
void deleteElement(ListNode*& head, int target) {
if (head == nullptr)
return;
if (head->data == target) {
ListNode* temp = head;
head = head->next;
delete temp;
return;
}
ListNode* curr = head;
while (curr->next != nullptr && curr->next->data != target)
curr = curr->next;
if (curr->next == nullptr)
return;
ListNode* toDelete = curr->next;
curr->next = curr->next->next;
delete toDelete;
}
// 输出链表元素
void printList(const ListNode* head) {
ListNode* temp = head;
while (temp != nullptr) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << "\n";
}
// 示例用法
int main() {
ListNode* listHead = createEmptyList();
// ...插入操作...
printList(listHead);
// 清理内存
destroyList(listHead);
return 0;
}
```
阅读全文
相关推荐
















