64,644
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
template<class Type> class list;
template<class Type>
class Node
{
public:
friend class list<Type>;
Node(): next(NULL) {}
Node(const Type& d,Node<Type>* n=NULL): data(d),next(n) {}
Type& Data() { return data; }
private:
Type data;
Node<Type>* next;
};
//
template<class Type>
class list
{
public:
class iterator
{
public:
iterator(): curptr(NULL) {}
iterator(Node<Type>* cur): curptr(cur) {}
iterator(const iterator& iter) { curptr=iter.curptr; }
iterator& operator=(const iterator& iter) { curptr=iter.curptr; return *this; }
bool operator==(const iterator& iter) { return curptr==iter.curptr; }
bool operator!=(const iterator& iter) { return !(curptr==iter.curptr); }
iterator& operator++() { curptr = curptr->next/*curptr++*/; return *this; }
iterator& operator++(int) { iterator temp(*this); curptr = curptr->next/*curptr++*/; return temp; }
Type operator*() { return curptr->Data(); }
private:
Node<Type>* curptr;
};
list() { head=tail=new Node<Type>; }
void push_back(const Type& t);
iterator begin() { return head->next; }
iterator end() { return NULL; }
void clear();
~list() { clear(); delete head; }
private:
Node<Type>* head;
Node<Type>* tail;
};
template<class Type>
void list<Type>::push_back(const Type& t)
{
tail->next=new Node<Type>(t);
tail=tail->next;
}
template<class Type>
void list<Type>::clear()
{
Node<Type>* p=head->next;
while(p)
{
head->next=p->next;
delete p;
p=head->next;
}
head->next=NULL;
}
int main()
{
list<int> l1;
for(int i=1;i<5;i++)
l1.push_back(i);
for(list<int>::iterator iter=l1.begin();iter!=l1.end(); ++iter) //迭代器有问题,不能正确输出,why?
std::cout<<*iter << std::endl;
return 0;
}