C++实现简易list链表(附C++代码)

说明

思路是采用环状链表结构,以一个空的节点做连接。

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;
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值