用C++实现一个有头结点的链表,要包含操作:返回链表大小、打印链表、检查一个值是否在链表中、增添一个值,若它不在链表中、删除一个值,若它在链表中
时间: 2024-09-22 09:09:25 浏览: 33
在C++中,我们可以使用结构体表示链表节点和头结点。以下是包含上述操作的链表类的简单实现:
```cpp
#include <iostream>
// 定义链表节点
struct Node {
int value;
Node* next;
Node(int v) : value(v), next(nullptr) {}
};
// 定义链表类
class LinkedList {
private:
Node* head;
public:
LinkedList() : head(nullptr) {}
// 返回链表大小(节点数量)
size_t size() const {
size_t count = 0;
Node* current = head;
while (current != nullptr) {
count++;
current = current->next;
}
return count;
}
// 打印链表
void print() const {
Node* current = head;
while (current != nullptr) {
std::cout << current->value << " ";
current = current->next;
}
std::cout << "\n";
}
// 检查值是否在链表中
bool contains(int val) const {
Node* current = head;
while (current != nullptr) {
if (current->value == val) {
return true;
}
current = current->next;
}
return false;
}
// 增添一个值(如果不存在于链表中)
void add(int val) {
if (!contains(val)) {
Node* newNode = new Node(val);
if (head == nullptr) {
head = newNode;
} else {
Node* last = head;
while (last->next != nullptr) {
last = last->next;
}
last->next = newNode;
}
}
}
// 删除一个值(如果存在)
void remove(int val) {
if (head != nullptr && head->value == val) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* prev = nullptr, *current = head;
while (current != nullptr && current->value != val) {
prev = current;
current = current->next;
}
if (current != nullptr) {
prev->next = current->next;
delete current;
}
}
};
int main() {
LinkedList list;
list.add(1);
list.add(2);
list.add(3);
list.print(); // 输出:1 2 3
std::cout << "Size: " << list.size() << std::endl; // 输出:3
std::cout << "Contains 2: " << (list.contains(2) ? "Yes" : "No") << std::endl; // 输出:Yes
list.remove(2);
list.print(); // 输出:1 3
return 0;
}
```
这个链表类包含了返回链表大小、打印链表、检查值是否在链表中以及添加和删除值的功能。在`main`函数中,我们演示了如何创建链表并执行这些操作。
阅读全文