说明
思路是采用环状链表结构,以一个空的节点做连接。
Show me the code
#include <iostream>
#include <string>
using namespace std;
// 定义节点类
template <class T>
class list_node {
public:
typedef list_node* node_ptr;
node_ptr pre = nullptr; // 前向指针
node_ptr next = nullptr; // 后向指针
T data; // 数据
};
// 链表类
template <class T>
class List {
private:
typedef list_node<T> node;
node * connectNode = new node;
typedef unsigned int len;
len list_len = 0;
public:
// 析构函数
~List() {}
// 默认构造函数
List() {
connectNode->next = connectNode;
connectNode->pre = connectNode;
}
void push_back(T data) {
// 创建一个node
node * thisNode = new node;
// 构建关系
thisNode->pre = connectNode->pre;
connectNode->pre->next = thisNode;
thisNode->next = connectNode;
connectNode->pre = thisNode;
// 赋值
thisNode->data = data;
++list_len;
}
void push_front(T data) {
// 创建一个node
node * thisNode = new node;
// 构建关系
thisNode->next = connectNode->next;
connectNode->next->pre = thisNode;
thisNode->pre = connectNode;
connectNode->next = thisNode;
// 赋值
thisNode->data = data;
++list_len;
}
node * begin() {
return connectNode->next;
}
node * end() {
return connectNode;
}
len size() {
return list_len;
}
bool empty() {
return this->begin() == this->end();
}
};
int main() {
// 实例化自定义链表
List<int> my_list;
// 向容器添加值
my_list.push_back(1); // 后端插入
my_list.push_back(2); // 后端插入
my_list.push_front(3); // 前端插入
// 从头遍历容器
cout << "从头遍历结果为:";
for (auto it = my_list.begin(); it != my_list.end(); it = it->next) {
cout << it->data << " ";
}
cout << endl;
// 输出容器大小
cout << "容器存放数据个数为:" << my_list.size() << endl;
}