设计单向链表结构(如下图)的SingleList模板类
时间: 2024-05-08 13:16:17 浏览: 10
```
template <typename T>
class SingleList {
private:
struct Node {
T data;
Node* next;
Node(const T& d = T{}, Node* n = nullptr)
: data{ d }, next{ n } {}
};
Node* head;
public:
SingleList() : head{ nullptr } {}
~SingleList() {
while (head) {
Node* p = head;
head = head->next;
delete p;
}
}
bool isEmpty() const { return head == nullptr; }
void pushFront(const T& val) {
head = new Node(val, head);
}
void popFront() {
if (isEmpty()) {
throw std::out_of_range("popFront() on empty SingleList");
}
Node* p = head;
head = head->next;
delete p;
}
const T& front() const {
if (isEmpty()) {
throw std::out_of_range("front() on empty SingleList");
}
return head->data;
}
T& front() {
if (isEmpty()) {
throw std::out_of_range("front() on empty SingleList");
}
return head->data;
}
};
```
注意:这里只实现了单向链表的基本操作,如需更完整的实现可以自行添加。