设计一个简单的单向链表类模板 List,并进行测试
时间: 2024-05-13 18:20:24 浏览: 6
好的,我可以为您设计一个简单的单向链表类模板 List。
以下是 List 类的代码实现:
```
template <typename T>
class List {
private:
struct Node {
T data;
Node* next;
Node(const T& newData, Node* newNext = nullptr) {
data = newData;
next = newNext;
}
};
Node* head;
public:
List() {
head = nullptr;
}
~List() {
while (head != nullptr) {
Node* temp = head;
head = head->next;
delete temp;
}
}
void insert(const T& data) {
Node* newNode = new Node(data, head);
head = newNode;
}
void remove(const T& data) {
Node* currentNode = head;
Node* previousNode = nullptr;
while (currentNode != nullptr && currentNode->data != data) {
previousNode = currentNode;
currentNode = currentNode->next;
}
if (currentNode != nullptr) {
if (previousNode == nullptr) {
head = currentNode->next;
}
else {
previousNode->next = currentNode->next;
}
delete currentNode;
}
}
void print() const {
Node* currentNode = head;
while (currentNode != nullptr) {
std::cout << currentNode->data << " ";
currentNode = currentNode->next;
}
std::cout << std::endl;
}
};
```
可以通过在 main 函数中进行测试,如下所示:
```
int main() {
List<int> list;
list.insert(1);
list.insert(2);
list.insert(3);
list.print(); // 输出:3 2 1
list.remove(2);
list.print(); // 输出:3 1
return 0;
}
```
希望这个单向链表类模板 List 能够满足您的需求。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)