设计一个不带头结点的单链表类
时间: 2024-05-09 17:14:51 浏览: 8
好的,以下是一个简单的不带头结点的单链表类的设计:
```
class LinkedList {
private:
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
Node* head;
public:
LinkedList() : head(nullptr) {}
~LinkedList() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
void add(int val) {
Node* newNode = new Node(val);
if (!head) {
head = newNode;
} else {
Node* curr = head;
while (curr->next) {
curr = curr->next;
}
curr->next = newNode;
}
}
bool remove(int val) {
if (!head) return false;
if (head->data == val) {
Node* temp = head;
head = head->next;
delete temp;
return true;
}
Node* curr = head;
while (curr->next && curr->next->data != val) {
curr = curr->next;
}
if (!curr->next) return false;
Node* temp = curr->next;
curr->next = curr->next->next;
delete temp;
return true;
}
bool search(int val) {
Node* curr = head;
while (curr) {
if (curr->data == val) {
return true;
}
curr = curr->next;
}
return false;
}
};
```
该类包含一个指向链表头部的指针,该指针为私有成员,因此只能在类内部访问。该类提供了三个公有方法:add、remove 和 search。add 方法用于向链表末尾添加一个值,remove 方法用于删除链表中的一个值,search 方法用于查找链表中是否存在一个值。析构函数用于释放链表中的所有节点。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)