编写自己的list容器

来源:互联网 发布:sop流程图软件 编辑:程序博客网 时间:2024/06/06 00:55
//编写自己的容器#include <iostream>#include <string>template<typename T>class List{public:    List()    {         _pHead = NULL;         _pTail = NULL;    }    struct Node    {        T data;        Node* pNext;    };    class iterator    {    public:        iterator()        {            _pCur = NULL;        }        iterator(Node* pNode)        {            _pCur = pNode;        }        bool operator != (const iterator& it)        {            return !(_pCur == it._pCur);        }        iterator operator ++(int)        {            iterator it(_pCur);            _pCur = _pCur->pNext;            return it;        }        T operator *()//取指针上的数据        {            return _pCur->data;        }        protected:        Node* _pCur;    };    void push_back(const T&val)    {        Node* pNew = new Node;        pNew->data = val;        pNew->pNext = NULL;        if(_pHead == NULL&& _pTail == NULL)        {            _pHead = pNew;            _pTail = pNew;        }        else        {            _pTail->pNext = pNew;            _pTail = pNew;        }    }    iterator begin()    {        return iterator(_pHead);    }    iterator end()    {        return iterator(_pTail->pNext);    }protected:    Node* _pHead;//头    Node* _pTail;//尾部};//#include<list>using namespace std;void main(){    List<int> lst;    lst.push_back(10);    lst.push_back(20);    lst.push_back(30);//    lst.push_back(40);    List<int>::iterator it;    for(it = lst.begin();it != lst.end();it++)    {        cout<<*it<<endl;    }}

0 0
原创粉丝点击