fork download
  1. #include<iostream>
  2. using namespace std;
  3. //前置声明
  4. template <typename T>
  5. class list;
  6.  
  7. template <typename T>
  8. class node
  9. {
  10. T data;
  11. node *next;
  12. public:
  13. node(T d = 0) :data(d), next(NULL)
  14. {
  15.  
  16. }
  17. friend class list<T>;
  18. };
  19. template <typename T>
  20. class list
  21. {
  22. public:
  23. list() :head(NULL)
  24. {
  25.  
  26. }
  27. void push(T data);
  28. void print();
  29. private:
  30. node<T> *head;
  31. };
  32. template <typename T>
  33. void list<T>::push(T data)
  34. {
  35. node<T> *s = new node<T>(data);
  36. if (!head)
  37. {
  38. head = s;
  39. return;
  40. }
  41. node<T> *p = head;
  42. while (p->next)
  43. {
  44. p = p->next;
  45. }
  46. p->next = s;
  47. }
  48. template <typename T>
  49. void list<T>::print()
  50. {
  51. node<T> *p = head;
  52. while (p)
  53. {
  54. cout << p->data << endl;
  55. p = p->next;
  56. }
  57. }
  58. int main()
  59. {
  60. list<int> a;
  61. a.push(1);
  62. a.push(2);
  63. a.push(3);
  64. a.push(5);
  65. a.print();
  66. }
Success #stdin #stdout 0s 2816KB
stdin
Standard input is empty
stdout
1
2
3
5