C++链表类
时间: 2023-07-10 18:18:51 浏览: 32
好的,我可以为您提供一个简单的C++链表类的模板代码,您可以根据自己的需要进行修改和使用:
```
#include <iostream>
template <typename T>
class Node {
public:
T data;
Node<T>* next;
Node(const T& d = T(), Node<T>* n = nullptr) : data(d), next(n) {}
};
template <typename T>
class LinkedList {
private:
Node<T>* head;
int size;
public:
LinkedList() : head(nullptr), size(0) {}
~LinkedList() {
while (head != nullptr) {
Node<T>* temp = head;
head = head->next;
delete temp;
}
}
void push_front(const T& data) {
Node<T>* temp = new Node<T>(data, head);
head = temp;
++size;
}
void push_back(const T& data) {
Node<T>* temp = new Node<T>(data);
if (head == nullptr) {
head = temp;
} else {
Node<T>* curr = head;
while (curr->next != nullptr) {
curr = curr->next;
}
curr->next = temp;
}
++size;
}
void pop_front() {
if (head == nullptr) {
return;
}
Node<T>* temp = head;
head = head->next;
delete temp;
--size;
}
void pop_back() {
if (head == nullptr) {
return;
}
if (head->next == nullptr) {
delete head;
head = nullptr;
--size;
return;
}
Node<T>* curr = head;
while (curr->next->next != nullptr) {
curr = curr->next;
}
delete curr->next;
curr->next = nullptr;
--size;
}
int get_size() const {
return size;
}
void print_list() const {
Node<T>* curr = head;
while (curr != nullptr) {
std::cout << curr->data << " ";
curr = curr->next;
}
std::cout << std::endl;
}
};
```
这个链表类包括了常见的链表操作:插入头节点、插入尾节点、删除头节点、删除尾节点、获取链表大小和打印链表。您可以根据需要进行修改和添加其他操作。