• <C++> list模拟实现


    目录

    前言

    一、list的使用

    1. list的构造函数

    2. list iterator的使用

    3. list capacity

    4. list modifiers 

    5. list的算法

    1. unique​

    2. sort

    3. merge

    4. remove

    5. splice 

    二、list模拟实现

    1. 设置节点类 && list类

    2. push_back 

    3. 迭代器 

    重载 *

    重载前置 ++

    重载后置++

    重载前置--

    重载后置-- 

    重载 != 

    重载 ==  

    begin() && end() 

    拷贝构造 && 析构函数

    const迭代器

    4. insert 

    5. erase

    6. size

    7. push_back && push_front && pop_back && pop_front 

    8. clear 

    9. list的析构函数 

    10. list的拷贝构造函数 

    11. empty_init 

    12. list的赋值运算符重载

    总结


    前言

            前面学习了string、vector的模拟实现,其两者相似,但今天要学习的list就又有新的不同

    列表是序列容器,允许在序列中的任意位置进行恒定时间插入和擦除操作,以及双向迭代。

    列表容器实现为双向链表;双向链表可以将它们包含的每个元素存储在不同且不相关的存储位置。排序通过与每个元素的关联在内部保持,该链接指向它前面的元素,并链接到它后面的元素。

    它们与forward_list非常相似:主要区别在于forward_list对象是单链表,因此它们只能向前迭代,以换取更小、更高效。

    与其他基本标准序列容器(数组、vector和 deque)相比,列表在已经获得迭代器的容器内任何位置插入、提取和移动元素方面通常表现更好,因此在大量使用这些元素的算法(如排序算法)中也是如此。

    与其他序列容器相比,
    lists 和 forward_lists 的主要缺点是它们无法通过其位置直接访问元素;例如,要访问列表中的第六个元素,必须从已知位置(如开始或结束)迭代到该位置,这需要它们之间的距离的线性时间。它们还会消耗一些额外的内存,以保持与每个元素关联的链接信息(这可能是大型小元素列表的重要因素)。


    一、list的使用

    1. list的构造函数

    构造函数(constructor)接口说明
    list()构造空的list
    list (size_type n, const value_type& val = value_type() )构造的list中包含n个值为val的元素
    list (const list& x)拷贝构造函数
    list (lnputlterator first, inputlterator last)用 [first, last)区间中的元素构造list

    2. list iterator的使用

    函数声明接口声明
    begin + end返回第一个元素的迭代器+返回最后一个元素下一个位置的迭代器
    rbegin + rend返回第一个元素的reserve_iterator,即end位置,返回最后一个元素下一个位置的reserve_iterator,即begin位置

    3. list capacity

    函数声明接口说明
    empty检查list是否为空,是返回true,否则返回false
    size返回list中有效结点的个数

    4. list modifiers 

    函数声明接口说明
    push_front
    在list首元素前插入值为val的元素
    pop_front
    删除list中第一个元素
    push_back
    在list尾部插入值为val的元素
    pop_back
    删除list中最后一个元素
    insert
    在list position 位置中插入值为val的元素
    erase
    删除list position位置的元素
    swap
    交换两个list中的元素
    clear
    清空list中的有效元素

            insert、erase 与string的 insert 不同,string的insert形参是下标,而vector、list的形参都是迭代器,但是list和vector还是有不同的,因为vector在第i个位置插入是begin() + i,而list就不能使用迭代器加数字,因为链表物理空间不连续,要实现加的代价有点大。

            要实现迭代器的改变,只能循环自加(重载的++)

    1. std::list<int> lt;
    2. lt.push_back(1);
    3. lt.push_back(2);
    4. lt.push_back(3);
    5. lt.push_back(4);
    6. auto it = lt.begin();
    7. for (size_t i = 0; i < 4; i++)
    8. {
    9. ++it;
    10. }
    11. lt.insert(it, 100);
    12. for (auto e : lt)
    13. {
    14. cout << e << " ";
    15. }
    16. cout << endl;

            如果我们想在元素3之前插入一个数据,我们应该使用find函数来查找,但是我们可以发现vector、list都没有find函数,这是因为STL将容器和算法分开了,提出了容器公共的算法。

            因为容器数据一般都是私有的,外部不能访问,但是各容器都是通过迭代器访问的,C++通过迭代器提取出了容器公共的算法,迭代器没有暴露原容器的细节,不管是树还是数组...,都是通过同样的方式访问

    1. it = c.begin();
    2. while (it != c.end())
    3. {
    4. cout << *it << " ";
    5. }

            循环条件也是关键,并不是 it < c.end( )  而是 it != c.end( ),这是因为容器的存储方式不一定连续存储

            

            【first,last)

            所以公共算法是通过迭代器实现的,例如find函数

    1. template<class InputIterator, class T>
    2. InputIterator find (InputIterator first, InputIterator last, const T& val)
    3. {
    4. while (first!=last) {
    5. if (*first==val) return first;
    6. ++first;
    7. }
    8. return last;
    9. }

            例如:

    1. auto it = find(lt.begin(), lt.end(), 3);
    2. if (it != lt.end())
    3. {
    4. lt.insert(it, 100);
    5. }
    6. for (auto e : lt)
    7. {
    8. cout << e << " ";
    9. }
    10. cout << endl;

            因为list不需要扩容,节点的地址不改变,所以list的insert就不存在失效的问题

            同理分析erase,迭代器指向的节点被释放,那么迭代器一定是失效的

    5. list的算法

            迭代器从功能上来说,分为:单向、双向、随机 三类迭代器,它是由容器的底层结构决定的

    单向:只能++            forward_list / 哈希

    双向:可以++ / --      list / map / set

    随机:++ / -- / + / -    vector / string / deque

            单向迭代器访问自由度小于双向小于随机。所以,单向迭代器可以使用的情况,双向、随机迭代器都可以访问。

            对于不同的容器,迭代器种类不同,是否使用alrorithm的算法情况也不同,例如sort函数,实现原理是快排,sort的形参只能使用随机迭代器

    1. std::list<int> lt;
    2. lt.push_back(1);
    3. lt.push_back(2);
    4. lt.push_back(3);
    5. lt.push_back(4);
    6. lt.push_back(5);
    7. //错误,随机sort需要随即迭代器,而list是双向迭代器
    8. //sort(lt.begin(), lt.end());
    9. for (auto e : lt)
    10. cout << e << " ";
    11. cout << endl;
    12. lt.reverse();
    13. lt.sort();
    14. for (auto e : lt)
    15. cout << e << " ";
    16. cout << endl;

            list的sort实现原理是归并排序,但是一旦数据量增大,list的sort就不合适了,效率还不如转到vector,vector排序后再转回list。

    所以,容器所提供的接口都是有讲究的,vector不提供专门的头插头删(只是复用insert),是因为如果它频繁的头插头删那么就不应该使用vector,而是list。

    再比如,list的sort,因为迭代器的原因,list需要自己实现sort,但是list它不是一个适合多次排序的容器,vector等随机迭代器才适合sort的快排算法,所以list的sort只适合少量数据的排序,数据量如果很大,那么就考虑更改容器来提高效率。

     1. unique

    • 去重函数,注意要先排序 ,不排序去重效率很低
    • 使用双指针进行去重操作

     2. sort

    • 双向迭代器

    3. merge

    • 两个有序链表的合并 
    • 第二个参数是仿函数

    4. remove

    •  等效于find + erase
    • 如果没找到,什么也不做,不会报错

    5. splice 

    • 转接链表,把 list1 的节点取下来,接到 list2 上 ’
    • 可以转接到自身,但是不能重叠,重叠会陷入死循环

    三个重载函数功能:

            1. 将链表x全部转移到position之前位置

            2. 将链表x的 i 迭代器处节点转移到position之前位置,即只转移一个节点

            3. 将链表x从first到last范围的节点全部转移到position之前位置

    例:

    1. int main()
    2. {
    3. std::list<int> mylist1, mylist2;
    4. std::list<int>::iterator it;
    5. // set some initial values:
    6. for (int i = 1; i <= 4; ++i)
    7. mylist1.push_back(i); // mylist1: 1 2 3 4
    8. for (int i = 1; i <= 3; ++i)
    9. mylist2.push_back(i * 10); // mylist2: 10 20 30
    10. it = mylist1.begin();
    11. ++it; // points to 2
    12. //将list2全部接在list1的2之前
    13. mylist1.splice(it, mylist2);
    14. //部分转移
    15. mylist1.splice(it, mylist2, ++mylist2.begin());
    16. mylist1.splice(it, mylist2, ++mylist2.begin(), mylist2.end());
    17. //转移到自身
    18. mylist1.splice(mylist1.begin(), mylist1, ++mylist1.begin(), mylist2.end());
    19. return 0;
    20. }

    二、list模拟实现

    1. 设置节点类 && list类

    • list_node采用struct类,因为struct默认是公有,用class也行,但是要加上public,如果不加公有条件,后续使用十分麻烦,还要搞友元

    1. template<class T>
    2. struct list_node
    3. {
    4. list_node* _next;
    5. list_node* _prev;
    6. T _val;
    7. };
    • C++的struct已经成为类,并且还有模板,所以list_node不是类型,list_node才是类型,为了避免书写时忘记,我们重命名
    • list成员变量即为头节点
    1. private:
    2. Node* _head;

    1. namespace my_list
    2. {
    3. template<class T>
    4. struct list_node
    5. {
    6. list_node* _next;
    7. list_node* _prev;
    8. T _val;
    9. };
    10. template<class T>
    11. class list
    12. {
    13. typedef list_node Node;
    14. private:
    15. Node* _head;
    16. };

    2. push_back 

    • 开辟新节点,新节点类型是一个类,new的时候会调用默认构造,我们再struct类中定义构造函数来构造新节点
    1. namespace my_list
    2. {
    3. template<class T>
    4. struct list_node
    5. {
    6. list_node* _next;
    7. list_node* _prev;
    8. T _val;
    9. //默认构造
    10. list_node(const T& val = T())
    11. :_next(nullptr)
    12. ,_prev(nullptr)
    13. ,_val(val)
    14. {}
    15. };
    16. template<class T>
    17. class list
    18. {
    19. typedef list_node Node;
    20. public:
    21. list()
    22. {
    23. _head = new Node;
    24. _head->_prev = _head;
    25. _head->_next = _head;
    26. }
    27. void push_back(const T& x)
    28. {
    29. Node* tail = _head->_prev;
    30. Node* newnode = new Node(x);
    31. tail->_next = newnode;
    32. newnode->_prev = tail;
    33. newnode->_next = _head;
    34. _head->_prev = newnode;
    35. }
    36. private:
    37. Node* _head;
    38. };
    39. }

    3. 迭代器 

    思考:直接将 Node* 作为 iterator 可以吗?

    答案:不能!

    原因

            1. 首先,Node*作为迭代器解引用得到的是结构体,不是数据

            2. 其次,节点地址不连续,迭代器++不能移动到下一个节点

    之前的vector、string的元素指针天生就有两点优势,所以它们的迭代器就用指针实现

    解决:

            使用运算符重载!将iterator封装为一个类,重载运算符 ++ 和 * 。iterator是自定义类型,它的成员是一个节点的指针

    list<int>::iterator it = lt.begin();

            属于类域的是在类内部定义的,一种为typedef的内嵌类型,另一种是内部类

    1. template<class T>
    2. struct __list_iterator
    3. {
    4. typedef list_node Node;
    5. //成员
    6. Node* _node;
    7. //默认构造
    8. __list_iterator(Node* _node)
    9. :_node(node)
    10. {}
    11. };
    • 在 list 内部,我们将__list_iterator 重定义为 iterator,切记用public修饰,因为我们需要在类外部使用迭代器
    • 之所以将迭代器命名为__list_iterator是为了避免重名,因为后面的容器都是需要iterator的

    重载 *

    • 迭代器解引用应为元素值
    1. //引用返回,因为节点生命周期不在该函数内
    2. //可读可写版本
    3. T& operator*()
    4. {
    5. return _node->_val;
    6. }

    重载前置 ++

    • 返回this解引用
    1. __list_iterator& operator++()
    2. {
    3. _node = _node->_next;
    4. return *this;
    5. }

    重载后置++

    1. //后置++
    2. __list_iterator operator++(int)
    3. {
    4. __list_iterator tmp(*this);
    5. _node = _node->_next;
    6. return tmp;
    7. }

    重载前置--

    1. //前置--
    2. self& operator--()
    3. {
    4. _node = _node->_prev;
    5. return *this;
    6. }

    重载后置-- 

    1. //后置--
    2. self operator--(int)
    3. {
    4. self tmp(*this);
    5. _node = _node->_prev;
    6. return tmp;
    7. }

    重载 != 

    • 这里注意const,因为比较!=时,右边时end(), 该函数返回的是临时对象,临时对象具有常性,所以需要const修饰
    1. //这里注意const,因为比较!=时,右边时end(),该函数返回的是临时对象,临时对象具有常性
    2. bool operator!=(const __list_iterator& it)
    3. {
    4. return _node != it._node;
    5. }

    重载 ==  

    • 复用即可
    1. bool operator==(const __list_iterator& it)
    2. {
    3. return _node == it._node;
    4. }

    begin() && end() 

    • 返回指针类型会隐式类型转换为iterator类,我们也可以直接返回匿名对象
    1. template<class T>
    2. struct __list_iterator
    3. {
    4. typedef list_node Node;
    5. //成员
    6. Node* _node;
    7. //默认构造
    8. __list_iterator(Node* node)
    9. :_node(node)
    10. {}
    11. //引用返回,因为节点生命周期不在该函数内
    12. //可读可写版本
    13. T& operator*()
    14. {
    15. return _node->_val;
    16. }
    17. __list_iterator& operator++()
    18. {
    19. _node = _node->_next;
    20. return *this;
    21. }
    22. //这里注意const,因为比较!=时,右边时end(),该函数返回的是临时对象,临时对象具有常性
    23. bool operator!=(const __list_iterator& it)
    24. {
    25. return _node != it._node;
    26. }
    27. };
    28. template<class T>
    29. class list
    30. {
    31. typedef list_node Node;
    32. public:
    33. //迭代器要公有,让外面可以使用
    34. typedef __list_iterator iterator;
    35. iterator begin()
    36. {
    37. //由指针类型隐式转换为iterator类
    38. //return _head->_next;
    39. //也可以用匿名对象
    40. return iterator(_head->_next);
    41. }
    42. iterator end()
    43. {
    44. return iterator(_head);
    45. }
    46. list()
    47. {
    48. _head = new Node;
    49. _head->_prev = _head;
    50. _head->_next = _head;
    51. }
    52. private:
    53. Node* _head;
    54. };
    55. }

     拷贝构造 && 析构函数

    list<int>::iterator it = lt.begin();

    1. 这里就是拷贝构造 it ,但是成员是内置类型Node*,浅拷贝正确吗?

            我们要的就是那个节点的指针,就是需要浅拷贝来访问该节点,所以对于iterator的拷贝构造我们仅仅就是需要浅拷贝即可,不需要深拷贝,所以编译器默认生成的就足够使用。

    2. 但是,我们要思考,多个迭代器对象指向同一个节点,会导致程序崩溃吗?

            浅拷贝导致程序崩溃的原因就是多次析构,但是每次使用完迭代器,就需要析构该节点吗?

            不可以!节点不属于迭代器,迭代器无权释放节点,迭代器仅仅是访问修改功能,有权限释放节点的是 list 的析构函数

    .

    所以,在实际的工作中,对于内置类型指针,需要浅拷贝or深拷贝是根据目标来决定的

     const迭代器

    如何设计const迭代器?

            

    typedef const __list_iterator const_iterator;

            这样设计可以吗?

            不可以!如果这样设计,迭代器本身就不能修改了。

            我们想实现的是迭代器指向的内容不能被修改,而迭代器本身可以++修改指向,如果使用上面的迭代器,那么我们就不能修改迭代器了,因为const迭代器对象就不能调用++函数,因为++函数没有const修饰,也不能加上const修饰,因为函数内要进行修改

            正确设计应将解引用重载函数的返回值设为const T&,

    但是又来了一个问题,我们需要再写一个除了解引用重载函数外一模一样的const_iterator类吗?

            代码冗余

    我们来看stl的解决方案:

    • 因为只有解引用的返回值不同,所以在这里我们可以使用模板参数控制返回值类型
    • 对 __list_iterator 重命名为self,方便日后再次修改模板时,不用再去修改各成员函数的返回值
    1. //typedef __list_iterator iterator;
    2. //typedef __list_iterator const_iterator;
    3. //对于const迭代器和普通迭代器,这属于两个类,根据模板生成相应的类
    4. template<class T, class Ref>
    5. struct __list_iterator
    6. {
    7. typedef list_node Node;
    8. typedef __list_iterator self;
    9. //成员变量
    10. Node* _node;
    11. __list_iterator(Node* node)
    12. :_node(node)
    13. {}
    14. //引用返回,因为节点生命周期不在该函数内
    15. //可读可写版本
    16. //Ref根据不同的参数,返回相应权限的引用
    17. Ref operator*()
    18. {
    19. return _node->_val;
    20. }
    21. //前置++
    22. self& operator++()
    23. {
    24. _node = _node->_next;
    25. return *this;
    26. }
    27. //后置++
    28. self operator++(int)
    29. {
    30. self tmp(*this);
    31. _node = _node->_next;
    32. return tmp;
    33. }
    34. //这里注意const,因为比较!=时,右边时end(),该函数返回的是临时对象,临时对象具有常性
    35. bool operator!=(const self& it)
    36. {
    37. return _node != it._node;
    38. }
    39. bool operator==(const self& it)
    40. {
    41. return _node == it._node;
    42. }
    43. };

            我们再来升级:

            可以看到STL的list模板有三个类型,并且list的重载函数重载了->。

    问:为什么要重载 ->呢?*解引用得不到数据吗?

    答:是的,对于其他的自定义类型,operator*确实得不到其中数据,例如

    1. struct A
    2. {
    3. A(int a1 = 0, int a2 = 0)
    4. :_a1(a1)
    5. ,_a2(a2)
    6. {}
    7. int _a1;
    8. int _a2;
    9. };
    10. void test()
    11. {
    12. list lt;

            编译错误,对于*it,解引用的结果是结构体,如果想要输出,要自己重载流插入和流提取,对于私有的变量,是需要自己重载,但是对于公有的变量,我们可以用 ->(*it)._a1来访问数据。用 -> 是因为迭代器模拟的就是指针 

            但是,it -> _a1本质其实是it -> -> _a1,因为第一个->是运算符重载,返回的是一个指针,后面没有运算符了,所以是访问不了数据的,能访问是因为 迭代器特殊处理,省略了一个->

            由于operator->返回值有两种类型,所以我们又加了一个模板参数Ptr

    template<class T, class Ref, class Ptr>

            所以对于复杂的代码,很难一步看懂,先省略细节,往后看

    4. insert 

    • 在pos之前插入,由于双向链表特性,pos在哪里都可以,即使是头节点,那就是尾插
    • 返回插入后的迭代器
    1. //在pos之前插入,由于双向链表特性,pos哪里都可以,即使是头节点
    2. iterator insert(iterator pos)
    3. {
    4. //这里就体现了struct比class优点,class是需要封装为私有的,后面还要搞友元
    5. Node* cur = pos._node;
    6. Node* prev = cur->_prev;
    7. Node* newnode = new Node(x);
    8. prev->_next = newnode;
    9. newnode->_next = cur;
    10. cur->_prev = newnode;
    11. newnode->_prev = prev;
    12. ++_size;
    13. return newnode;
    14. }

    5. erase

    • erase就需要判断pos是否合法
    • 返回删除后的下一个迭代器
    1. iterator erase(iterator pos)
    2. {
    3. assert(pos != end());
    4. Node* cur = pos._node;
    5. Node* prev = cur->_prev;
    6. Node* next = cur->_next;
    7. prev->_next = next;
    8. next->_prev = prev;
    9. delete cur;
    10. --_size;
    11. return next;
    12. }

    6. size

    • 可以遍历一遍,时间复杂度是O(N)
    • 也可以加一个_size成员变量,记录size
    1. size_t size()
    2. {
    3. /*size_t sz = 0;
    4. iterator it = begin();
    5. while (it != end())
    6. {
    7. ++sz;
    8. ++it;
    9. }
    10. return sz;*/
    11. //也可增加一个_size的成员变量
    12. return _size;
    13. }

    7. push_back && push_front && pop_back && pop_front 

    • 全部复用insert、erase即可
    1. void push_back(const T& x)
    2. {
    3. /*Node* tail = _head->_prev;
    4. Node* newnode = new Node(x);
    5. tail->_next = newnode;
    6. newnode->_prev = tail;
    7. newnode->_next = _head;
    8. _head->_prev = newnode;*/
    9. insert(end(), x);
    10. }
    11. void push_front(const T& x)
    12. {
    13. insert(beign(), x);
    14. }
    15. void pop_back()
    16. {
    17. erase(--end());
    18. }
    19. void pop_front()
    20. {
    21. erase(begin());
    22. }

    8. clear 

    • 清除数据,除了头节点
    1. //清数据,不需要清除头节点
    2. void clear()
    3. {
    4. iterator it = beign();
    5. while (it != end())
    6. {
    7. //不要++it,迭代器失效
    8. it = erase(it);
    9. }
    10. _size = 0;
    11. }

    9. list的析构函数 

    • 复用clear函数
    1. ~list()
    2. {
    3. //复用clear
    4. clear();
    5. delete _head;
    6. _head = nullptr;
    7. }

    10. list的拷贝构造函数 

    • 逐个push_back即可
    1. //拷贝构造
    2. list(const list& lt)
    3. {
    4. _head = new Node;
    5. _head->_prev = _head;
    6. _head->_next = _head;
    7. _size = 0;
    8. for (auto& e : lt) //引用是为了防止数组类型很大
    9. {
    10. push_back(e);
    11. }
    12. }

    11. empty_init 

    • 因为构造和拷贝构造都需要四行初始化,所以我们封装为empty_init函数
    1. void empty_init()
    2. {
    3. _head = new Node;
    4. _head->_prev = _head;
    5. _head->_next = _head;
    6. _size = 0;
    7. }

    12. list的赋值运算符重载

    • 现代写法
    1. void swap(list& lt)
    2. {
    3. std::swap(_head, lt._head);
    4. std::swap(_size, lt._size);
    5. }
    6. list& operator=(list lt) //赋值运算符重载的现代写法
    7. {
    8. swap(lt);
    9. return *this;
    10. }

            注意:对于拷贝构造和赋值运算符重载,STL的list中这两个函数声明时,返回值是list&,而我们写的是list&list是类型,list是类名,写类型是必然正确的,但是这里写类名也对,编译器也可以识别。 

            类模板在类里既可以写类名又可以写类型但是不推荐缩写类型名

    整体代码

    1. #pragma once
    2. #include
    3. #include
    4. #include
    5. namespace my_list
    6. {
    7. template<class T>
    8. struct list_node
    9. {
    10. //成员
    11. list_node* _next;
    12. list_node* _prev;
    13. T _val;
    14. //默认构造
    15. list_node(const T& val = T())
    16. :_next(nullptr)
    17. ,_prev(nullptr)
    18. ,_val(val)
    19. {}
    20. };
    21. //typedef __list_iterator iterator;
    22. //typedef __list_iterator const_iterator;
    23. //对于const迭代器和普通迭代器,这属于两个类,根据模板生成相应的类
    24. template<class T, class Ref, class Ptr>
    25. struct __list_iterator
    26. {
    27. typedef list_node Node;
    28. typedef __list_iterator self;
    29. //成员变量
    30. Node* _node;
    31. __list_iterator(Node* node)
    32. :_node(node)
    33. {}
    34. //引用返回,因为节点生命周期不在该函数内
    35. //可读可写版本
    36. //Ref根据不同的参数,返回相应权限的引用
    37. Ref operator*()
    38. {
    39. return _node->_val;
    40. }
    41. //第三个模板参数,T* 和 const T*
    42. Ptr operator->()
    43. {
    44. return &(_node->_val);
    45. }
    46. //前置++
    47. self& operator++()
    48. {
    49. _node = _node->_next;
    50. return *this;
    51. }
    52. //后置++
    53. self operator++(int)
    54. {
    55. self tmp(*this);
    56. _node = _node->_next;
    57. return tmp;
    58. }
    59. //前置--
    60. self& operator--()
    61. {
    62. _node = _node->_prev;
    63. return *this;
    64. }
    65. //后置--
    66. self operator--(int)
    67. {
    68. self tmp(*this);
    69. _node = _node->_prev;
    70. return tmp;
    71. }
    72. //这里注意const,因为比较!=时,右边时end(),该函数返回的是临时对象,临时对象具有常性
    73. bool operator!=(const self& it)
    74. {
    75. return _node != it._node;
    76. }
    77. bool operator==(const self& it)
    78. {
    79. return _node == it._node;
    80. }
    81. };
    82. template<class T>
    83. class list
    84. {
    85. typedef list_node Node;
    86. public:
    87. typedef __list_iterator iterator; //迭代器要公有,让外面可以使用
    88. typedef __list_iteratorconst T&, const T*> const_iterator;
    89. iterator begin()
    90. {
    91. //由指针类型隐式转换为iterator类
    92. //return _head->_next;
    93. //也可以用匿名对象
    94. return iterator(_head->_next);
    95. }
    96. iterator end()
    97. {
    98. return iterator(_head);
    99. }
    100. const_iterator beign() const
    101. {
    102. return const_iterator(_head->next);
    103. }
    104. const_iterator end() const
    105. {
    106. return const_iterator(_head);
    107. }
    108. void empty_init()
    109. {
    110. _head = new Node;
    111. _head->_prev = _head;
    112. _head->_next = _head;
    113. _size = 0;
    114. }
    115. list()
    116. {
    117. /*_head = new Node;
    118. _head->_prev = _head;
    119. _head->_next = _head;
    120. _size = 0;*/
    121. //因为构造和拷贝构造都需要这四行初始化,所以我们封装为empty_init
    122. empty_init();
    123. }
    124. //拷贝构造
    125. list(const list& lt)
    126. {
    127. /*_head = new Node;
    128. _head->_prev = _head;
    129. _head->_next = _head;
    130. _size = 0;*/
    131. empty_init();
    132. for (auto& e : lt) //引用是为了防止数组类型很大
    133. {
    134. push_back(e);
    135. }
    136. }
    137. void swap(list& lt)
    138. {
    139. std::swap(_head, lt._head);
    140. std::swap(_size, lt._size);
    141. }
    142. //list是类型
    143. list& operator=(list lt) //赋值运算符重载的现代写法
    144. {
    145. swap(lt);
    146. return *this;
    147. }
    148. ~list()
    149. {
    150. //复用clear
    151. clear();
    152. delete _head;
    153. _head = nullptr;
    154. }
    155. //清数据,不需要清除头节点
    156. void clear()
    157. {
    158. iterator it = beign();
    159. while (it != end())
    160. {
    161. //不要++it,迭代器失效
    162. it = erase(it);
    163. }
    164. _size = 0;
    165. }
    166. void push_back(const T& x)
    167. {
    168. /*Node* tail = _head->_prev;
    169. Node* newnode = new Node(x);
    170. tail->_next = newnode;
    171. newnode->_prev = tail;
    172. newnode->_next = _head;
    173. _head->_prev = newnode;*/
    174. insert(end(), x);
    175. }
    176. void push_front(const T& x)
    177. {
    178. insert(beign(), x);
    179. }
    180. void pop_back()
    181. {
    182. erase(--end());
    183. }
    184. void pop_front()
    185. {
    186. erase(begin());
    187. }
    188. //在pos之前插入,由于双向链表特性,pos哪里都可以,即使是头节点
    189. iterator insert(iterator pos)
    190. {
    191. //这里就体现了struct比class优点,class是需要封装为私有的,后面还要搞友元
    192. Node* cur = pos._node;
    193. Node* prev = cur->_prev;
    194. Node* newnode = new Node(x);
    195. prev->_next = newnode;
    196. newnode->_next = cur;
    197. cur->_prev = newnode;
    198. newnode->_prev = prev;
    199. ++_size;
    200. return newnode;
    201. }
    202. iterator erase(iterator pos)
    203. {
    204. assert(pos != end());
    205. Node* cur = pos._node;
    206. Node* prev = cur->_prev;
    207. Node* next = cur->_next;
    208. prev->_next = next;
    209. next->_prev = prev;
    210. delete cur;
    211. --_size;
    212. return next;
    213. }
    214. size_t size()
    215. {
    216. /*size_t sz = 0;
    217. iterator it = begin();
    218. while (it != end())
    219. {
    220. ++sz;
    221. ++it;
    222. }
    223. return sz;*/
    224. //也可增加一个_size的成员变量
    225. return _size;
    226. }
    227. private:
    228. Node* _head;
    229. size_t _size;
    230. };
    231. }

    总结

            list相较于vector、string最重要的是迭代器的设计,list因为数据类型、储存方式而需要独特的迭代器——类来实现,除此之外,list无更多新的内容,对于反向迭代器,会在之后的适配器同意讲解。下节,我们来学习stack、queue。

            最后,如果小帅的本文哪里有错误,还请大家指出,请在评论区留言(ps:抱大佬的腿),新手创作,实属不易,如果满意,还请给个免费的赞,三连也不是不可以(流口水幻想)嘿!那我们下期再见喽,拜拜!

  • 相关阅读:
    javascript中数组和对象的解构
    VirtualBox安装CentOS 7教程
    2023昆明理工大学计算机考研信息汇总
    process.env环境变量配置方式(配置环境变量区分开发环境和生产环境)
    照片图片 动漫化 卡通化
    面向对象之抽象类的认识 - (java语法)
    最新版SpringBoot整合Mybatis,实现增删改查(CRUD)
    AWS SAA C003 Test --EBS snapshot
    黑马程序员2023新版JavaWeb企业开发全流程学习笔记(涵盖Spring+MyBatis+SpringMVC+SpringBoot等)
    P2824 [HEOI2016/TJOI2016] 排序
  • 原文地址:https://blog.csdn.net/prodigy623/article/details/134107108