C++实现一个list
时间: 2023-10-24 14:09:03 浏览: 43
下面是一个简单的 C++ 实现双向链表的 list 类:
```cpp
#include <iostream>
template <typename T>
class List {
private:
struct Node {
T data;
Node* prev;
Node* next;
Node(const T& d = T{}, Node* p = nullptr, Node* n = nullptr)
: data{ d }, prev{ p }, next{ n } {}
Node(T&& d, Node* p = nullptr, Node* n = nullptr)
: data{ std::move(d) }, prev{ p }, next{ n } {}
};
Node* head;
Node* tail;
int size;
public:
List() : head{ new Node{} }, tail{ head }, size{ 0 } {}
~List() {
while (head != nullptr) {
Node* p = head;
head = head->next;
delete p;
}
}
void push_back(const T& val) {
tail->next = new Node{ val, tail, nullptr };
tail = tail->next;
++size;
}
void push_front(const T& val) {
head->next = new Node{ val, head, head->next };
if (tail == head) {
tail = head->next;
}
++size;
}
void pop_back() {
if (tail != head) {
Node* p = tail;
tail = tail->prev;
tail->next = nullptr;
delete p;
--size;
}
}
void pop_front() {
if (head->next != nullptr) {
Node* p = head->next;
head->next = p->next;
if (p->next != nullptr) {
p->next->prev = head;
}
else {
tail = head;
}
delete p;
--size;
}
}
int length() const {
return size;
}
bool empty() const {
return size == 0;
}
void display() const {
Node* p = head->next;
while (p != nullptr) {
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
};
```
使用示例:
```cpp
int main() {
List<int> lst;
lst.push_back(1);
lst.push_back(2);
lst.push_back(3);
lst.push_front(0);
lst.push_front(-1);
lst.push_front(-2);
lst.display(); // -2 -1 0 1 2 3
lst.pop_back();
lst.pop_front();
lst.display(); // -1 0 1 2
std::cout << "Length: " << lst.length() << std::endl; // Length: 4
return 0;
}
```