C++ 使用模板实现一个List的实例

C++ 使用模板实现一个List的实例,第1张

概述C++使用模板写的一个Listtemplate<classT>classList{private:structNode{Tdata;Node*next;};//head

C ++使用模板写的一个List

template<class T> class List { private:   struct Node   {     T data;     Node *next;   };   //head   Node *head;   //size   int length;    //process   Node *p;    //temp   Node *q; public:   List()   {     head = NulL;     length = 0;     p = NulL;   }   voID add(T t)   {     if(head == NulL)     {       q = new Node();       q->data = t;       q->next = NulL;       length ++ ;       head = q ;       p = head;     }     else     {       q = new Node();       q->data = t;       q->next = NulL;       length ++;       p -> next = q;       p = q;     }   }    voID remove(int n)   {     if(n >= length )     {       return;     }     length -- ;      //删除头节点     if(n == 0)     {       q = head ;       head = head -> next;       delete(q);     }     else     {       q = head;       for(int i = 0 ; i < n-1 ; i++)       {         q = q -> next;       }       Node *t = q ->next;       q->next = q->next ->next;       delete(t);      }      //     p = head;     if (p != NulL)     {       while(p->next != NulL)       {         p = p->next;       }     }    }    int getSize()   {     return length;   }    int getLength()   {     return getSize();   }    T get(int n)   {     q = head;     for (int i = 0 ;i < n ; i++)     {       q = q->next;     }     return q->data;   }   }; 

调用方式如下

List<Stu>List;   Stu stu1;   Stu stu2;   Stu stu3;   stu1.username = "1";   stu2.username = "2";   stu3.username = "3";    List.add(stu1);   List.remove(0);   List.add(stu2);   List.add(stu3);    for (int i = 0 ;i < List.getSize() ; i ++)   {     cout << List.get(i).username;   } 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

总结

以上是内存溢出为你收集整理的C++ 使用模板实现一个List的实例全部内容,希望文章能够帮你解决C++ 使用模板实现一个List的实例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1245030.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存