整数链表 用类模板实现通用的链表类
时间: 2024-02-02 14:03:35 浏览: 28
您好!感谢您的提问。下面是一个用类模板实现通用的整数链表类的示例代码:
```cpp
template <typename T>
class LinkedList {
private:
struct Node {
T data;
Node* next;
Node(const T& value) : data(value), next(nullptr) {}
};
Node* head;
int size;
public:
LinkedList() : head(nullptr), size(0) {}
~LinkedList() {
clear();
}
void insert(const T& value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
size++;
}
void remove(const T& value) {
if (head == nullptr) {
return;
}
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
size--;
return;
}
Node* current = head;
while (current->next != nullptr) {
if (current->next->data == value) {
Node* temp = current->next;
current->next = current->next->next;
delete temp;
size--;
return;
}
current = current->next;
}
}
void clear() {
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
head = nullptr;
size = 0;
}
int getSize() const {
return size;
}
};
```
使用该链表类时,可以传递任意类型的整数(例如 `int`、`long`等)作为模板参数,如下所示:
```cpp
LinkedList<int> intList;
intList.insert(10);
intList.insert(20);
intList.insert(30);
intList.remove(20);
std::cout << "Size: " << intList.getSize() << std::endl;
```
这样,就可以创建一个整数链表并进行插入、删除等操作了。希望对您有所帮助!如有任何疑问,请随时提问。