设计一个简单的单向链表类模版List,并进行测试。
时间: 2024-03-07 12:47:00 浏览: 52
好的,下面是设计的单向链表类模版List的代码,其中包含了节点类Node和链表类List:
```c++
#include <iostream>
template<typename T>
class Node {
public:
T data;
Node* next;
Node(T data) {
this->data = data;
next = nullptr;
}
};
template<typename T>
class List {
private:
Node<T>* head;
public:
List() {
head = nullptr;
}
~List() {
Node<T>* current = head;
while (current != nullptr) {
Node<T>* next = current->next;
delete current;
current = next;
}
}
void add(T data) {
Node<T>* node = new Node<T>(data);
if (head == nullptr) {
head = node;
} else {
Node<T>* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = node;
}
}
void print() {
Node<T>* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
};
```
下面是对List类进行测试的代码:
```c++
int main() {
List<int> list;
list.add(1);
list.add(2);
list.add(3);
list.print();
return 0;
}
```
输出结果为:
```
1 2 3
```
可以看到,List类的测试结果是正确的。
阅读全文