自定义list

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

 
 #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;
 
    }
}
 
 

猜你喜欢

转载自www.cnblogs.com/countryboy666/p/10943318.html
今日推荐