用c++设计一个带头结点的单链表类,要求: (1)带头结点单链表类的成员函数包括取数据元素个数、插入元素、删除所有值为k的元素、取数据元素。 (2)设计一个测试主函数,实际运行验证所设计循环单链表类的正确性
时间: 2024-11-25 21:14:24 浏览: 8
在C++中,我们可以创建一个带头节点的单链表类`ListWithHeader`,包含相应的成员函数来满足需求。下面是一个简单的实现:
```cpp
#include <iostream>
// 定义链表节点结构
struct Node {
int data;
Node* next;
Node(int value = 0): data(value), next(nullptr) {}
};
// 带头节点单链表类
class ListWithHeader {
private:
Node* head; // 链表头部指针
public:
// 构造函数
ListWithHeader() : head(new Node()) {}
// 取数据元素个数
size_t getLength() const {
size_t count = 0;
Node* current = head;
while (current != nullptr) {
++count;
current = current->next;
}
return count;
}
// 插入元素
void insert(int value) {
Node* newNode = new Node(value);
if (head->data == 0) { // 如果链表为空,直接将新节点设为头节点
head = newNode;
} else {
Node* last = head;
while (last->next != nullptr) {
last = last->next;
}
last->next = newNode;
}
}
// 删除所有值为k的元素
void removeElements(int k) {
if (head == nullptr || head->data != k) return; // 如果链表空或头节点不是k,直接返回
Node* current = head;
while (current->next != nullptr && current->next->data == k) {
Node* temp = current->next;
delete temp;
current->next = temp->next;
}
}
// 取数据元素
int getData(size_t index) const {
if (index >= getLength()) throw std::out_of_range("Index out of range");
Node* current = head;
for (size_t i = 0; i < index; ++i) {
current = current->next;
}
return current->data;
}
// 主函数(仅用于测试)
static void testList(ListWithHeader& list) {
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
list.removeElements(30);
std::cout << "Length: " << list.getLength() << std::endl;
try {
std::cout << "Data at index 0: " << list.getData(0) << std::endl;
std::cout << "Data at index 1: " << list.getData(1) << std::endl;
std::cout << "Data at index 3 (should throw exception): " << list.getData(3) << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "Caught expected exception: " << e.what() << std::endl;
}
}
~ListWithHeader() {
Node* temp = head;
while (temp != nullptr) {
Node* next = temp->next;
delete temp;
temp = next;
}
}
};
int main() {
ListWithHeader list;
list.testList(list);
return 0;
}
```
阅读全文