码迷,mamicode.com
首页 > 其他好文 > 详细

自定义list

时间:2019-05-29 14:23:09      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:一个   需要   art   insert   type   splay   begin   ring   迭代器   

//思路分析: 定一个链表类,成员有 (节点,迭代器)

 

 

#include <iostream>

using namespace std;

//节点
template<typename U>
class Node
{
  public:
    Node(){pNext == NULL;}
    Node(U data):m_data(data){pNext = NULL;}
    U m_data;
    Node<U>* pNext;
};
//list  底层是链表
template <typename U>
class Mylist
{
public:

    // Mylist<int>::Myiterator iter;
    //迭代  底层是一个指针  ++ -- *
    struct Myiterator
    {


        Myiterator(Node<U> *node = NULL)
        {
            pNode = node;
        }
        Myiterator &operator++(int)
        {
            pNode= pNode->pNext;
            return *this;

        }
        bool operator !=(const Myiterator &other)
        {
            return pNode!=other.pNode;

        }
        U operator *()
        {
            return pNode->m_data;

        }
         Node<U> *pNode;
    };
    //  list<int> list; list.begin();返回的是迭代器
    //成员函数
    Myiterator begin()
    {
        Myiterator iter(m_pfrist);
        return iter;
    }
    Myiterator end()
    {
       Myiterator iter(NULL);
        return iter;
    }
     Mylist():m_ilen(0){m_pfrist =NULL;}
    void insert(U data);
    void display();

private:
    int m_ilen;
    //产生对象需要加<U>
    Node<U> *m_pfrist;
};
//插入
template<typename U>
void Mylist<U>::insert(U data)
{
    Node<U>* node= new Node<U>(data);
    if(NULL == m_pfrist)
    {
        m_pfrist=node;

    }else{

        node->pNext = m_pfrist;
        m_pfrist = node;

    }
m_ilen++;
}
//打印
template<typename U>
void Mylist<U>::display()
{
    Node<U> *node= m_pfrist;
    while(node != NULL)
    {
        cout<<node->m_data<<endl;
        node = node->pNext;

    }

}

struct STU
{
    STU(const string name="STU",float score=0.0): m_strName(name),m_fscore(score){}
    string m_strName;
    float m_fscore;

};
ostream& operator<<(ostream &os,const STU stu)
{
    os<<stu.m_strName<<" "<<stu.m_fscore<<endl;
    return os;

}
int main()
{
    Mylist<STU> stull;
   // ll.insert(88);
    stull.insert(STU("JACK",88.99));
    stull.insert(STU("ROSE",88.99));
    stull.insert(STU("Jim",33.99));
    stull.display();
    Mylist<STU>::Myiterator iter;
    iter = stull.begin();
    for(;iter!=stull.end();iter++)
    {
        cout<<*iter<<endl;

    }
}

自定义list

标签:一个   需要   art   insert   type   splay   begin   ring   迭代器   

原文地址:https://www.cnblogs.com/countryboy666/p/10943318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!