使用c++ 创建一个初始长度为8个数据的链表 选择插入数据 删除数据 最后判断线性表是否为空
时间: 2024-11-25 20:14:56 浏览: 7
在C++中创建一个初始长度为8的数据链表,我们通常会使用结构体表示节点,并定义一个指向头节点的指针。以下是简单的步骤:
```cpp
#include <iostream>
// 定义链表节点结构
struct ListNode {
int data;
ListNode* next;
ListNode(int val = 0) : data(val), next(nullptr) {}
};
// 链表类
class LinkedList {
private:
ListNode* head;
public:
LinkedList() : head(nullptr) {}
// 插入数据
void insertData(int value) {
if (head == nullptr) {
head = new ListNode(value);
} else {
ListNode* newNode = new ListNode(value);
newNode->next = head;
head = newNode;
}
}
// 删除数据
bool deleteData(int value) {
if (head == nullptr) {
return false; // 空链表,无法删除
}
ListNode* current = head;
while (current != nullptr && current->data != value) {
current = current->next;
}
if (current == nullptr) {
return false; // 没找到要删除的节点
}
ListNode* temp = current->next;
delete current;
current = temp;
if (current == nullptr) {
head = nullptr; // 如果删除的是头节点,更新头指针
} else {
head = current;
}
return true;
}
// 判断链表是否为空
bool isEmpty() {
return head == nullptr;
}
~LinkedList() {
// 清理内存
while (head != nullptr) {
ListNode* temp = head;
head = head->next;
delete temp;
}
}
};
int main() {
LinkedList list;
for (int i = 0; i < 8; i++) {
list.insertData(i);
}
std::cout << "Is the list empty? " << (list.isEmpty() ? "Yes" : "No") << std::endl;
int removeValue = 5;
list.deleteData(removeValue);
std::cout << "After deleting " << removeValue << ", is the list empty? " << (list.isEmpty() ? "Yes" : "No") << std::endl;
return 0;
}
```
阅读全文