分享一份c++stl库list简单模拟实现。
如果能帮到你的话请点个免费的赞吧!!!!!
#pragma once
#include<assert.h>namespace my_list {template<class T>class ListNode {typedef ListNode<T> Node;public://list中需要访问node中的元素,所以用公有Node* _prev;Node* _next;T _val;//初始化ListNode(const T& val = T()):_val( val),_prev(nullptr),_next(nullptr){}};//ref是t的引用,Ptr是t的指针template<class T,class Ref ,class Ptr>class ListIterator {typedef ListNode<T> Node;typedef ListIterator<T,Ref,Ptr> iterator;public:Node* _Node;ListIterator(Node* node):_Node(node){}Ref operator*() {return _Node->_val;}Ptr operator->(){return &_Node->_val;}//++ititerator& operator++() {_Node = _Node->_next;return *this;}//it++iterator operator++(int) {iterator tmp(*this);_Node = _Node->_next;return tmp;}//--ititerator& operator--() {_Node = _Node->_prev;return *this;}//it++iterator operator--(int) {iterator tmp(*this);_Node = _Node->_prev;return tmp;}bool operator!=(const iterator& it) {return it._Node != _Node;}bool operator==(const iterator& it) {return it._Node == _Node;}};template<class T>class List {typedef ListNode<T> Node;Node* _head;size_t _size;public:typedef List<T> list;typedef ListIterator<T, T&, T*> iterator;typedef ListIterator<T ,const T& ,const T*> const_iterator;void Init(){_head = new Node;_head->_next = _head;_head->_prev = _head;_size = 0;}List(){Init();}List(const List<T>& it) {Init();for (auto e : it){push_back(e);}}list& operator=(list A) {swap(A);return *this;}iterator begin() {return _head->_next;}iterator end() {return _head;}const_iterator begin() const {return _head->_next;}const_iterator end() const {return _head;}void insert(iterator it, T val) {Node* tmp = new Node(val);Node* prev = it._Node->_prev;Node* next = it._Node;prev->_next = tmp, tmp->_prev = prev;next->_prev = tmp, tmp->_next = next;_size++;}void push_back(T val){insert(end(), val);}void push_front(T val){insert(begin(), val);}iterator earse(iterator it){Node* node = it._Node;Node* prev = node->_prev;Node* next = node->_next;delete node;prev->_next = next;next->_prev = prev;_size--;return next;}void pop_back() {earse(begin());}void pop_front() {earse(--end());}void swap(list A){std::swap(_head, A._head);std::swap(_size, A._size);}size_t size() {return _size;}void clear() {iterator it = begin();while (it != end()){it = earse(it);}}~List() {clear();delete _head;_head = nullptr;}};