List实现
2015-07-16 13:57
190 查看
#include<iostream> #include<algorithm> #include<iterator> using namespace std; template<typename T> struct list_node{ T key; list_node<T> *next,*pre; }; //关于用户自定义iterator,参见《The C++ Standard Library》7.5.2节 template<typename T> struct list_iterator:public iterator <bidirectional_iterator_tag,T/*,void,void,void*/>{ using ref=list_iterator<T>; using list_type=list_node<T>*; list_type node; list_iterator(list_type x):node(x){} list_iterator(){} T operator*() const {return node->key;} ref& operator++(){ node=node->next; return *this;} ref operator++(int){ auto tmp=*this; ++*this; return tmp; } ref& operator--(){ node=node->pre; return *this; } ref operator--(int){ auto tmp=*this; --*this; return tmp; } bool operator!=(const list_iterator<T>&x){ return node!=x.node; } bool operator==(const list_iterator<T>& x) const { return node == x.node; } }; template<typename T> class list{ public: using link_type=list_node<T>*; using list_type=list_node<T>; using iterator=list_iterator<T>; private: link_type start,tail; unsigned int count; public: list():count(0),start(new list_type),tail(new list_type){ start->next=tail; start->pre=nullptr; tail->pre=start; tail->next=nullptr; } ~list(){ clear(); delete start; delete tail;} public: void insert(iterator iter,const T& data){ link_type tmp=new list_type; tmp->key=data; tmp->next=iter.node; tmp->pre=iter.node->pre; iter.node->pre->next=tmp; iter.node->pre=tmp; ++count; } void push_back(const T& data){ insert(end(),data); } void push_front(const T& data){ insert(begin(),data); } void erase(iterator iter){ iter.node->next->pre=iter.node->pre; iter.node->pre->next=iter.node->next; delete iter.node; --count; } void pop_back(){ auto tmp=end(); erase(--tmp); } void pop_front(){ erase(begin()); } iterator begin(){ return static_cast<link_type>(start->next); } iterator end() { iterator tmp(tail); return tmp; } bool empty()const{ return count==0;} void clear(){ while(!empty()) pop_back(); } int size()const{ return count;} T front(){ return start->next->key;} T back(){ return tail->pre->key;} }; int main() { list<int> li; for(int i=0;i<200;++i){ if((i&1)==0) li.push_back(i); } auto p=li.end(); advance(p,-2); cout<<*p; }
相关文章推荐
- shell-自动部署war包到tomcat
- Linux LVM学习总结——扩展卷组VG
- 动态主机配置协议(DHCP)如何启动和关闭
- Linux下Web服务器环境搭建LNMP一键安装包 v2.6
- 值类型数据和引用类型数据
- CATALOG DATABASE command
- C++虚基类
- 阿里音乐:前脚送走刘春宁,后脚迎来高晓松(咱不谈颜值,只聊音
- 普通视图和物化视图的区别
- Unity3D研究院之通过C#使用Advanced CSharp Messenger(五十)
- Linux下Web服务器环境搭建LNMP一键安装包 v2.6
- 股市成本
- 拓扑排序还能这么写 zoj 2997
- poj 2762 Going from u to v or from v to u? (推断它是否是一个薄弱环节图)
- Android学习之播放背景音乐
- 项目开发之插件的安装 分类: ios开发 2015-07-16 13:56 183人阅读 评论(0) 收藏
- 大一下學期學習生活總結
- GRE写作必备句型
- MR21 VS MR22 对CKMLCP结果影响
- Activity生命周期的回调,你应该知道得更多!--Android源码剖析(下)