STL-模拟实现List
来源:互联网 发布:阿里云ecs安装lamp 编辑:程序博客网 时间:2024/05/17 02:04
在STL中的List并不单单只是一个链表,其结构设计特别精妙。
简单来说,其结构为:一个带头结点的双向循环链表。
主要代码实现:
#include <iostream>#include <assert.h>using namespace std;template<typename T>struct ListNode{ListNode* _next;ListNode* _prev;T _data;ListNode(const T& x):_data(x), _next(NULL), _prev(NULL){}};template<typename T, typename Ref, typename Ptr> //迭代器struct ListIterator{typedef ListNode<T> Node;typedef ListIterator<T, Ref, Ptr> Self;Node* _node;ListIterator(){}ListIterator(Node* node):_node(node){}bool operator!=(const Self& s){return _node != s._node;}Ref operator*(){return _node->_data;}Ptr 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<typename T>class List{typedef ListNode<T> Node;public:typedef ListIterator<T, T&, T*> Iterator;typedef ListIterator<T, const T&, const T*> ConstIterator;public:List():_head(BuyNewNode(T())){_head->_next = _head;_head->_prev = _head;}~List(){Node* tmp = _head->_next;while (tmp != _head){delete tmp->_prev;tmp=tmp->_next;}_head = NULL;}void PushBack(const T& x){//Node* tmp = BuyNewNode(x);//_head->_prev->_next = tmp;//tmp->_prev = _head->_prev;//_head->_prev= tmp;//tmp->_next = _head;Insert(End(),x);}void PopBack(){Erase(--End());}void PushFront(const T& x){Insert(Begin(), x);}void PopFront(){Erase(Begin());}Iterator Insert(Iterator pos, const T& x){assert(pos._node);Node* cur = pos._node;Node* prev = cur->_prev;Node* tmp = BuyNewNode(x);prev->_next = tmp;tmp->_prev = prev;tmp->_next = cur;cur->_prev = tmp;return tmp;}Iterator Erase(Iterator pos){assert(pos._node && pos._node != _head);Node* cur = pos._node;Node* prev = cur->_prev;Node* next = cur->_next;prev->_next = next;next->_prev = prev;delete cur;cur = NULL;return next;}Iterator Begin(){//return Iterator(_head->_next);return _head->_next;}Iterator End(){return Iterator(_head);}ConstIterator Begin()const{return ConstIterator(_head->_next);}ConstIterator End()const{return ConstIterator(_head);}protected:Node* _head;private:Node* BuyNewNode(const T& x){//次处应该是空间配置器return new Node(x);}};
1 0
- <STL>模拟实现List
- STL-模拟实现List
- 【STL】模拟实现list
- 数据结构::模拟STL实现list
- 模拟实现STL中的list
- 模拟实现STL中的list
- STL模拟实现List+迭代器
- 【STL】list的应用和模拟实现
- 【STL】 list的应用及模拟实现
- 【STL】list的应用模拟实现
- 【STL】迭代器与List的模拟实现
- 【STL】list迭代器的模拟实现
- 模拟实现STL中的List容器
- 类模板模拟实现STL中List
- 使用List模拟实现STL中的Queue
- 迭代器模拟实现STL中的list
- 【C++】模拟实现STL中的list
- STL容器中list与迭代器iterator的模拟实现
- leetCode -Array 154. Find Minimum in Rotated Sorted Array II
- java web中的一些简单操作(二)
- 粗浅看 java反射机制
- 划分方法聚类(二)K-MEANS算法的改进
- JS—事件对象
- STL-模拟实现List
- 第三方工具通过javamail发送邮件
- 能量项链
- C# 6 与 .NET Core 1.0 高级编程
- Java反射最佳实践
- 对回调函数的理解
- 解析java泛型(二)
- 在运行期通过反射了解JVM内部机制
- 搜索--PAT.A1091[BFS]