设计一个单向链表类模板
时间: 2024-03-05 20:48:35 浏览: 83
好的,以下是一个简单的单向链表类模板的设计:
```c++
template<typename T>
class LinkedListNode {
public:
T data; // 存储节点数据
LinkedListNode<T>* next; // 存储指向下一个节点的指针
LinkedListNode(T data) {
this->data = data;
this->next = nullptr;
}
};
template<typename T>
class LinkedList {
private:
LinkedListNode<T>* head; // 存储指向链表头节点的指针
public:
LinkedList() {
this->head = nullptr;
}
~LinkedList() {
LinkedListNode<T>* current = this->head;
while (current != nullptr) {
LinkedListNode<T>* next = current->next;
delete current;
current = next;
}
}
void add(T data) {
LinkedListNode<T>* node = new LinkedListNode<T>(data);
if (this->head == nullptr) {
this->head = node;
} else {
LinkedListNode<T>* current = this->head;
while (current->next != nullptr) {
current = current->next;
}
current->next = node;
}
}
void remove(T data) {
LinkedListNode<T>* current = this->head;
LinkedListNode<T>* previous = nullptr;
while (current != nullptr) {
if (current->data == data) {
if (previous == nullptr) {
this->head = current->next;
} else {
previous->next = current->next;
}
delete current;
return;
}
previous = current;
current = current->next;
}
}
void print() {
LinkedListNode<T>* current = this->head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
```
该链表类具有添加节点、删除节点和打印链表等基本功能。其中,节点类`LinkedListNode`包含了节点数据和指向下一个节点的指针;链表类`LinkedList`包含了指向链表头节点的指针,以及添加、删除和打印链表的方法。
阅读全文