设计一个简单的单向链表类模板,并进行测试
时间: 2023-12-30 20:03:02 浏览: 61
单向链表类模板(全)C++
好的,我可以回答您的第一个问题。
以下是一个简单的单向链表类模板的示例:
```c++
template<typename T>
class LinkedList {
private:
struct Node {
T data;
Node* next;
Node(const T& d, Node* n = nullptr) : data(d), next(n) {}
};
Node* head;
public:
LinkedList() : head(nullptr) {}
~LinkedList() {
Node* curr = head;
while (curr != nullptr) {
Node* temp = curr;
curr = curr->next;
delete temp;
}
}
void pushBack(const T& value) {
if (head == nullptr) {
head = new Node(value);
} else {
Node* curr = head;
while (curr->next != nullptr) {
curr = curr->next;
}
curr->next = new Node(value);
}
}
T popBack() {
if (head == nullptr) {
throw std::out_of_range("List is empty");
} else if (head->next == nullptr) {
T value = head->data;
delete head;
head = nullptr;
return value;
} else {
Node* curr = head;
while (curr->next->next != nullptr) {
curr = curr->next;
}
T value = curr->next->data;
delete curr->next;
curr->next = nullptr;
return value;
}
}
};
```
此模板包括节点结构体和链表类模板,可通过 pushBack 插入值并通过 popBack 获取末尾值。您可以通过以下代码段测试它:
```c++
LinkedList<int> list;
list.pushBack(1);
list.pushBack(2);
std::cout << list.popBack() << std::endl; // 输出 2
std::cout << list.popBack() << std::endl; // 输出 1
```
希望这个回答能帮到您!
阅读全文