链表类模板¶
约 5 个字 66 行代码 预计阅读时间 1 分钟
#include <iostream>
template<typename T>
struct Node {
T data;
Node* next;
Node(const T& value) : data(value), next(nullptr) {}
};
template<typename T>
class LinkedList {
private:
Node<T>* head;
Node<T>* tail;
public:
LinkedList() : head(nullptr), tail(nullptr) {}
~LinkedList() {
// 释放链表中的所有节点
Node<T>* current = head;
while (current != nullptr) {
Node<T>* next = current->next;
delete current;
current = next;
}
head = tail = nullptr;
}
// 在链表尾部添加节点
void add(const T& value) {
Node<T>* newNode = new Node<T>(value);
if (head == nullptr) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
// 打印链表内容
void display() const {
Node<T>* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
int main() {
// 测试链表类模板实现方式
LinkedList<int> list;
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
std::cout << "Linked List content: ";
list.display();
return 0;
}