温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中怎么实现一个单向链表

发布时间:2021-07-19 17:51:28 来源:亿速云 阅读:95 作者:Leah 栏目:编程语言

C++中怎么实现一个单向链表,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

C++单向链表实现代码:

  1. #include < iostream>   

  2. using namespace std;   

  3. template < class T>   

  4. struct node   

  5. {   

  6. //public:   

  7. // 结构体成员默认就是public的  

  8. T data;   

  9. node< T> *next;   

  10. };   

  11. //typedef struct node NODE;   

  12. //typedef NODE *NODEPTR;   

  13. //typedef后面要跟具体的类类型,而不是一个类模版。eg: typedef node< T> 
    NODE (C++中,实例化结构体时struct可省略)  

  14. template < class T>   

  15. class list   

  16. {   

  17. public:  

  18. //以下三个函数要供外部调用,所以要声明为public,class默认为private。  

  19. /*  

  20. void creat(T &p);   

  21. void print(T p);   

  22. void destroy(T &p);   

  23. */  

  24. //这三个函数的参数有问题,按照下文的实现,我认为应改为如下:  

  25. void creat(T *p);  

  26. void print(T *p);  

  27. void destroy(T *p);  

  28. };   

  29. template< class A>   

  30. //void creat(A &p)   

  31. void list< A>::creat(A *p)  

  32. {   

  33. //class node *q;   

  34. //形参里的A就是这个程序的node类型  

  35. char ch = 0; //下数第4行cin>>ch 中的ch未定义,在此补充  

  36. A *q = NULL;  

  37. q=p; //必须新增这一句,q用于以后的动态分配  

  38. cout< < "input"< < endl;   

  39. cin>>ch;  

  40. // if(!p) //这个if放在while里会影响效率,故移到while外边,
    改过程序之后,实际上用不着了  

  41. // {   

  42. //p=new struct node;   

  43. //语法错误,形参里的A就是这个程序的node类型  

  44. // p = new A();  

  45. if(ch!='#')  

  46. p->data=ch;   

  47. // }   

  48. cin>>ch;  

  49. while(ch!='#')   

  50. {   

  51. //q->next=new class node;   

  52. //语法错误,形参里的A就是这个程序的node类型  

  53. q->next = new A();  

  54. //q->next=ch;   

  55. //这句应该是给data赋值  

  56. q->next->data = ch;  

  57. qq = q->next; //必须新增这一句,q用于以后的动态分配  

  58. cin>>ch;   

  59. }   

  60. q->next=NULL;   

  61. }   

  62. template < class T>   

  63. void list< T>::print(T *p)   

  64. {   

  65. if(p)   

  66. {   

  67. cout< < p->data< < " ";   

  68. print(p->next);   

  69. }   

  70. }  

  71. template < class T>   

  72. void list< T>::destroy(T *p)   

  73. {   

  74. if(p)   

  75. {   

  76. destroy(p->next);   

  77. delete p->next;   

  78. }   

  79. }   

  80. int main()   

  81. {   

  82. // NODEPTR p;   

  83. node< int> p;  

  84. // list L; 模版要有参数  

  85. list<  node< int> > L;  

  86. L.creat(&p);   

  87. cout < <  endl < <  endl < <  "show:" < < endl;  

  88. L.print(&p);   

  89. L.destroy(&p);  

  90. return 0;   

关于C++中怎么实现一个单向链表问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI