fork download
  1. #include <iostream>
  2.  
  3. template <class T>
  4. class LinkList
  5. {
  6. private:
  7.  
  8. struct ListNode
  9. {
  10. T value1;
  11. struct ListNode *next;
  12. };
  13.  
  14. ListNode *head; // List head pointer
  15.  
  16. void destroy(); // utility function
  17.  
  18. public:
  19. //***Constructor***
  20. LinkList();
  21. LinkList(const LinkList&);
  22.  
  23. //***Destructor***
  24. ~LinkList();
  25.  
  26. LinkList& operator=(LinkList);
  27.  
  28. //***LinkList Operations***
  29. void append(T);
  30. // removed insert since it's invariants are violated by append.
  31. void display(std::ostream& stream) const;
  32. };
  33.  
  34. template <class T>
  35. void LinkList<T>::display(std::ostream& os) const
  36. {
  37. unsigned index = 0;
  38.  
  39. ListNode* current = head;
  40.  
  41. while (current)
  42. {
  43. os << index++ << ": " << current->value1 << '\n';
  44. current = current->next;
  45. }
  46. }
  47.  
  48. //Implimentation for LinkList
  49. template <class T>
  50. void LinkList<T>::destroy()
  51. {
  52. ListNode* current = head;
  53.  
  54. while (current)
  55. {
  56. ListNode* next = current->next;
  57. delete current;
  58. current = next;
  59. }
  60.  
  61. head = nullptr;
  62. }
  63.  
  64. //***Constructor***
  65. template <class T>
  66. LinkList<T>::LinkList() : head(nullptr)
  67. {
  68. }
  69.  
  70. template <class T>
  71. LinkList<T>::LinkList(const LinkList<T>& list) : head(nullptr)
  72. {
  73. ListNode* current = list.head;
  74.  
  75. while (current)
  76. {
  77. append(current->value1);
  78. current = current->next;
  79. }
  80. }
  81.  
  82. template <class T>
  83. LinkList<T>& LinkList<T>::operator=(LinkList list)
  84. {
  85. destroy();
  86. head = list.head;
  87. list.head = nullptr;
  88.  
  89. return *this;
  90. }
  91.  
  92.  
  93. //***Destructor***
  94. template <class T>
  95. LinkList<T>::~LinkList()
  96. {
  97. destroy();
  98. }
  99.  
  100.  
  101. //***LinkList Operations***
  102. template <class T>
  103. void LinkList<T>::append(T val1)
  104. {
  105. ListNode* n = new ListNode;
  106. n->value1 = val1;
  107. n->next = nullptr;
  108.  
  109. if (head == nullptr)
  110. head = n;
  111. else
  112. {
  113. ListNode* current = head;
  114.  
  115. while (current->next)
  116. current = current->next;
  117.  
  118. current->next = n;
  119. }
  120. }
  121.  
  122. int main()
  123. {
  124. LinkList<int> a;
  125. a.append(3);
  126. a.append(2);
  127. a.append(1);
  128. a.display(std::cout);
  129. std::cout << '\n';
  130.  
  131. LinkList<int> b(a); // copy constructor
  132. b.display(std::cout);
  133. std::cout << '\n';
  134.  
  135. LinkList<int> c;
  136. c = a; // copy assignment
  137. c.display(std::cout);
  138. std::cout << '\n';
  139. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
0: 3
1: 2
2: 1

0: 3
1: 2
2: 1

0: 3
1: 2
2: 1