zoukankan      html  css  js  c++  java
  • c/c++:一个带迭代器的链表模板 iterator

    #include<iostream>
    using namespace std;
    
    template<class T>
    struct Unit
    {
        public:
        Unit * next;
        T value;
    };
    template<class T>
    class MyLink
    {
    public:
    
        class LinkIterator
        {
            private:
            Unit<T> * init;
            public:
            LinkIterator(Unit<T> * init)
            {
                this->init=init;
            }
            bool operator !=(LinkIterator& it)
            {
                return this->init!=it.init;
            }
            void operator ++(int)
            {
                this->init=init->next;
            }
            Unit<T> operator *()
            {
                return *init;
            }
        };
    private:
        Unit<T> *head;
        Unit<T> *prev;
        Unit<T> *hail;
    public:
        MyLink()
        {
            head=prev=hail=NULL;
        }
        void Add(T value)
        {
            Unit<T>* unit=new Unit<T>();
            unit->value=value;
            unit->next=NULL;
            if(NULL==head)
            {
                head=prev=unit;
            }
            else
            {
                prev->next=unit;
                prev=unit;
            }
            hail=unit->next;
        }
        Unit<T> *Begin()
        {
            return head;
        }
        Unit<T> *End()
        {
            return hail;
        }
        virtual ~MyLink()
        {
            prev=head;
            Unit<T>* next;
            while(NULL!=prev)
            {
                next=prev->next;
                delete prev;
                prev=next;
            }
        }
    };
    
    template<class T>
    ostream& operator<< (ostream& os, const Unit<T>& s)
    //全局重载操作符
    {
        os<<s.value;
        return os;
    }
    
    template<class T>
    void display (T begin, T end)
    {
        for(T mid=begin;mid!=end; mid ++)
            cout<<*mid<<" ";
        cout<<endl;
    }
    
    int main()
    {
        MyLink<int> ml;
        for(int i=0;i<5;i++)
            ml.Add(i+1);
        MyLink<int>:: LinkIterator start=ml.Begin();
        MyLink<int>:: LinkIterator end=ml.End();
        display(start,end);
        return 0;
    }
  • 相关阅读:
    BAM部署失败 未能加载”AdomdClient”或它的某一个依赖项。系统找不到指定的文件
    BizTalk Server 事务机制
    TSQL 访问远程数据库并对其数据表进行操作
    BAM门户聚合 – Pivot Table不显示数据
    Find max or min
    SetProperties
    Define
    Form derives from Form
    MWArrayComponent
    JAVA JDK
  • 原文地址:https://www.cnblogs.com/Azhu/p/2586394.html
Copyright © 2011-2022 走看看