迭代器(list迭代器的實現)
阿新 • • 發佈:2018-12-25
class List
{
typedef _ListNode<T> Node;
public:
typedef _ListIterator<T, T&, T*> Iterator;
typedef _ListIterator<T, const T&, const T*> ConstIterator;
typedef ReserveIterator<Iterator> ReserveIterator;
//typedef ReserveIterator<ConstIterator> ConstReserveIterator ;
List()
{
_head = new Node(T());
_head->_next = _head;
_head->_prev = _head;
}
void clear()
{
Iterator it = Begin();
while (it!= End())
{
Node* del = it._node;
it++;
delete del;
}
}
~List ()
{
clear();
delete _head;
_head = NULL;
}
Iterator End()
{
return Iterator(_head);
}
ConstIterator End() const
{
return ConstIterator(_head);
}
ReserveIterator REnd()
{
return ReserveIterator(End());
}
/*ConstReserveIterator REnd() const
{
return ConstReserveIterator(End());
}*/
ReserveIterator RBegin()
{
return ReserveIterator(--End());
}
/*ConstReserveIterator RBegin() const
{
return ConstReserveIterator(End());
}*/
Iterator Begin()
{
return Iterator(_head->_next);
}
ConstIterator Begin() const
{
return ConstIterator(_head->_next);
}
Node* Buynode(const T& x)
{
Node* newnode = new Node(x);
return newnode;
}
void Insert(Iterator pos, const T& x)//在pos位置前插入
{
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* temp = Buynode(x);
temp->_prev = prev;
prev->_next = temp;
temp->_next = cur;
cur->_prev = temp;
}
void Erase(Iterator& pos)
{
assert(pos != _head);
Node* cur = pos._node;
Node* prev = cur->_prev;
Node* next = cur->_next;
prev->_next = next;
next->_prev = prev;
delete cur;
}
void PushBack(const T& data)
{/*
Node* temp = Buynode(data);
Node* tail = _head->_prev;
temp->_prev = tail;
tail->_next = temp;
temp->_next = _head;
_head->_prev = temp;*/
Insert(End(), data);
}
void PushFront(const T& data)
{
Insert(Begin(), data);
}
void PopBack()
{
Erase(--End());
}
void PopFront()
{
Erase(Begin());
}
void PrintList()
{
Iterator it = Begin();
while (it != End())
{
cout << *it << " ";
it++;
}
cout << endl;
}
protected:
Node* _head;
};
void TestList()
{
List<int> l;
l.PushBack(1);
l.PushBack(2);
l.PushBack(3);
l.PushBack(4);
//l.PrintList();
///*l.PopBack();
//l.PopBack();
//l.PopBack();
//l.PopBack();*/
//l.PushFront(8);
//l.PushFront(0);
//l.PrintList();
//l.PopFront();
//l.PopFront();
//l.PopFront();
//l.PrintList();
List<int>::ReserveIterator it = l.RBegin();
while (it != l.REnd())
{
cout << *it << " ";
it++;
}
cout << endl;
}