如何在C++中实现单链表的基本操作,包括插入、查找和删除节点?请提供模板类实现的示例代码。
时间: 2024-10-26 15:09:39 浏览: 25
在《数据结构实践:单链表的前插、后插、查找与删除操作》一文中,你可以找到对单链表基本操作的详细介绍。为了更好地理解这些操作,这里将提供一个完整的模板类实现示例,涵盖插入、查找和删除节点等核心功能。
参考资源链接:[数据结构实践:单链表的前插、后插、查找与删除操作](https://wenku.csdn.net/doc/5g9o9axu29?spm=1055.2569.3001.10343)
首先,定义链表节点和链表的模板类:
```cpp
#include <iostream>
template<class T>
struct Node {
T data;
Node<T>* next;
};
template<class T>
class LinkList {
private:
Node<T>* head;
public:
LinkList() : head(nullptr) {}
~LinkList() {
Node<T>* current = head;
while (current != nullptr) {
Node<T>* toDelete = current;
current = current->next;
delete toDelete;
}
}
void Insert(T x) {
Node<T>* newNode = new Node<T>{x, head};
head = newNode;
}
void InsertAfter(T x, T afterValue) {
Node<T>* current = head;
while (current != nullptr && current->data != afterValue) {
current = current->next;
}
if (current != nullptr) {
Node<T>* newNode = new Node<T>{x, current->next};
current->next = newNode;
}
}
bool Remove(T x) {
Node<T>** prev = &head;
while (*prev != nullptr) {
if ((*prev)->data == x) {
Node<T>* toDelete = *prev;
*prev = toDelete->next;
delete toDelete;
return true;
}
prev = &((*prev)->next);
}
return false;
}
void RemoveAll(T x) {
while (Remove(x));
}
void PrintList() const {
Node<T>* current = head;
while (current != nullptr) {
std::cout << current->data <<
参考资源链接:[数据结构实践:单链表的前插、后插、查找与删除操作](https://wenku.csdn.net/doc/5g9o9axu29?spm=1055.2569.3001.10343)
阅读全文