标签:c++
#pragma once template<class T> struct __ListNode { __ListNode<T>* _next; __ListNode<T>* _prev; T _data; __ListNode(const T& x = T()) :_next(NULL) ,_prev(NULL) ,_data(x) {} }; template<class T, class Ref, class Ptr> struct __ListIterator { typedef __ListIterator<T, Ref, Ptr> Self; typedef T ValueType; typedef Ref Reference; typedef Ptr Pointer; ////////////////////////////////////////////////////////////////////////// __ListNode<T>* _node; ////////////////////////////////////////////////////////////////////////// __ListIterator() {} __ListIterator(__ListNode<T>* x) :_node(x) {} bool operator==(const Self& s) { return _node == s._node; } bool operator!=(const Self& s) { return _node != s._node; } Reference operator*() { return _node->_data; } //前置++ Self& operator++() { _node = _node->_next; return *this; } //后置++ Self operator++(int) { Self tmp(*this); _node = _node->_next; return tmp; } //前置-- Self& operator--() { _node = _node->_prev; return *this; } //后置-- Self operator--(int) { Self tmp(*this); _node = _node->_prev; return tmp; } }; template<class T> class List { public: typedef __ListNode<T> ListNode; typedef __ListIterator<T, T&, T*> Iterator; List() { _head = new ListNode; _head->_next = _head; _head->_prev = _head; } void Insert(Iterator pos, const T& x) { ListNode* cur = pos._node; ListNode* prev = cur->_prev; ListNode* tmp = new ListNode(x); prev->_next = tmp; tmp->_next = cur; tmp->_prev = prev; cur->_prev = tmp; } void PushBack(const T& x) { Insert(End(), x); } void PushFront(const T& x) { Insert(Begin(), x); } void PopBack() { Erase(--End()); } Iterator Erase(Iterator pos) { assert(!pos.End()); ListNode* prev = pos._node->_prev; ListNode* next = pos._node->_next; prev->_next = next; next->_prev = prev; delete pos._node; return Iterator(next); } Iterator Begin() { return Iterator(_head->_next); } Iterator End() { return Iterator(_head); } protected: ListNode* _head; }; void Test() { List<int> list; list.PushBack(1); list.PushBack(2); list.PushBack(3); list.PushBack(4); List<int>::Iterator it = list.Begin(); while (it != list.End()) { *it = 10; cout<<*it<<" "; ++it; } cout<<endl; }
本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1827262
标签:c++
原文地址:http://zgw285763054.blog.51cto.com/11591804/1827262