容器是c++stl库里实现的重要结构,这里简单实现链表的构造以及遍历操作。
在stl库里实现了容器的迭代器,用于遍历容器中的部分或全部元素。
在这里我们来模拟实现迭代器的简单遍历,以及容器迭代器接口的实现。
//节点
template
struct ListNode
{
ListNode(const T& data)
:_next(NULL), _prev(NULL), _data(data)
{
}
T _data;
ListNode
* _next;
ListNode
* _prev;
};
//带头结点的循环双向链表
template
class List
{
typedef ListNode
Node; public: typedef _Iterator
Iterator; typedef _Iterator
ConstIterator; Node* GetNode(const T& x) { return new Node(x); } List()//构造函数 :_head(GetNode(T()) ) { _head->_next = _head; _head->_prev = _head; } ~List()//析构函数 { Clean(); delete _head; } Iterator Begin()//迭代器接口,返回一个用第一个元素的指针构造的迭代器 { return Iterator(_head->_next); } ConstIterator Begin()const { return ConstIterator(_head->_next); } Iterator End() { return Iterator(_head); } ConstIterator End()const { return ConstIterator(_head); } void Clean() { Node* Pnode = _head->_next; while (Pnode != _head) { Node* del = Pnode; Pnode = Pnode->_next; delete del; } } void pushback(const T& x)//尾插元素 { Node* tail = _head->_prev; Node* temp = GetNode(x); tail->_next = temp; temp->_prev = tail; temp->_next = _head; _head->_prev = temp; } protected: Node* _head; };
#include
using namespace std;
//节点
template
struct ListNode
{
ListNode(const T& data)
:_next(NULL), _prev(NULL), _data(data)
{
}
T _data;
ListNode
* _next;
ListNode
* _prev;
};
//迭代器
template
struct _Iterator { typedef ListNode
Node; typedef _Iterator
Self; _Iterator(Node* node) :_node(node) {} Ref operator*() //*操作符重载 { return _node->_data; } Self& operator++()//++操作符重载 { _node = _node->_next; return *this; } bool operator!=(const Self& it) const//!=操作符重载 { return it._node != _node; } Node* _node; }
迭代器是容器的内嵌类,通过实现迭代器的++,*,!= 操作符,以及在容器类通过Begin和End函数实现遍历容器的作用。
一下是测试代码
PrintMyList用以实现的迭代器打印链表
void PrintMyList(const List
& l1)//遍历并打印链表
{
List
::ConstIterator it = l1.Begin();
{
while (it != l1.End())
{
cout << *it << " ";
++it;
}
cout << endl;
}
}
int main()
{
List
l1;
l1.pushback(1);
l1.pushback(2);
l1.pushback(3);
PrintMyList(l1);
system("pause");
return 0;
}