首页 > 代码库 > list C++实现
list C++实现
模仿STL中list,实现了其大部分功能。list能够高效地利用内存资源,常数时间的插入删除操作。而且,list除了erase外,不怎么存在迭代器失效的现象。
#include<iostream> #include<iterator> #include<algorithm> using namespace std; template<class T> struct _List_node{ typedef void* void_pointer; void_pointer next; void_pointer prev; T data; }; template<class T,class Ref,class Ptr> class _List_iterator{ public: typedef _List_iterator<T, T&, T*> iterator; typedef _List_iterator<T, const T&, const T*> const_iterator; typedef _List_iterator<T, Ref, Ptr> self; typedef T value_type; typedef Ptr pointer; typedef Ref reference; typedef _List_node<T>* link_type; typedef size_t size_type; typedef ptrdiff_t difference_type; link_type node; _List_iterator(link_type x):node(x){} _List_iterator(){} _List_iterator(const iterator &x):node(x.node){} bool operator== (const iterator& x )const{return node == x.node;} bool operator!= (const iterator& x)const{return node != x.node;} reference operator*()const{return (*node).data;} pointer operator->()const{return &(operator*());} T operator *(){return node->data;} iterator &operator++(int){ iterator tmp = *this; ++*this; return tmp; } iterator& operator++(){ node = (link_type)((*node).next); return *this; } iterator& operator--(){ node = (link_type)((*node).prev); return *this; } iterator& operator--(int){ iterator tmp = *this; --*this; return tmp; } }; template<class T> class List{ public: typedef _List_node<T>* link_type; typedef _List_iterator<T,T&,T*> iterator; typedef T value_type; typedef T* pointer; typedef T& reference; typedef size_t size_type; typedef ptrdiff_t difference_type; protected: typedef _List_node<T> list_node; link_type node; //..... public: List(){create_node();} List(List& alist){ create_node(); for(List<T>::iterator ite=alist.begin();ite!=alist.end();++ite) push_back(*ite); } iterator begin(){return (link_type)((*node).next);} iterator end(){return node;} bool empty()const{return node->next == node;} size_type size()const{ size_type result = 0; distance(begin(),end(),result); return result; } reference front(){return *begin();} reference back(){return *(--end());} iterator insert(iterator position,const T& x){ link_type tmp = create_node(x); tmp->next = position.node; tmp->prev = position.node->prev; (link_type(position.node->prev))->next = tmp; position.node->prev = tmp; return tmp; } link_type create_node(const T& x){ link_type p = new list_node; p->data = http://www.mamicode.com/x;>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。