fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <initializer_list>
  4.  
  5. template <class T>
  6. class LinkedList
  7. {
  8. private:
  9. struct node
  10. {
  11. T data;
  12. node *next;
  13. } *head = nullptr;
  14. public:
  15. // Constructors and destructors
  16. LinkedList() = default;
  17. ~LinkedList();
  18. LinkedList(const std::initializer_list<T> &il);
  19. LinkedList(std::istream &is);
  20.  
  21. // Member functions
  22. void push (T data);
  23. LinkedList<T>& reverse();
  24. std::ostream &print(std::ostream &os);
  25. };
  26.  
  27. template <class T>
  28. LinkedList<T>::~LinkedList()
  29. {
  30. node *cur = head, *next = nullptr;
  31. while (cur)
  32. {
  33. next = cur->next;
  34. delete cur;
  35. cur = next;
  36. }
  37. }
  38.  
  39. template <class T>
  40. LinkedList<T>::LinkedList(const std::initializer_list<T> &il)
  41. {
  42. for (const auto &data : il)
  43. push (data);
  44. }
  45.  
  46. template <class T>
  47. LinkedList<T>::LinkedList(std::istream &is)
  48. {
  49. T temp;
  50. while (is >> temp)
  51. push (temp);
  52. }
  53.  
  54. // Push to head
  55. template <class T>
  56. void LinkedList<T>::push (T data)
  57. {
  58. node *elem = new node;
  59. elem->data = data;
  60. elem->next = head;
  61. head = elem;
  62. }
  63.  
  64. template <class T>
  65. LinkedList<T>& LinkedList<T>::reverse()
  66. {
  67. node *prev = nullptr;
  68. node *next = nullptr;
  69. if (!head) return *this;
  70. while (head->next)
  71. {
  72. next = head->next;
  73. head->next = prev;
  74. prev = head;
  75. head = next;
  76. }
  77. head->next = prev;
  78. return *this;
  79. }
  80.  
  81. template <class T>
  82. std::ostream& LinkedList<T>::print(std::ostream &os)
  83. {
  84. node *iter = head;
  85. while (iter)
  86. {
  87. os << iter->data << " ";
  88. iter = iter->next;
  89. }
  90. return os;
  91. }
  92.  
  93.  
  94. int main()
  95. {
  96. // Integers
  97. LinkedList<int> list({1, 2, 3, 4, 5});
  98. list.print(std::cout) << std::endl;
  99. list.reverse();
  100. list.print(std::cout) << std::endl;
  101.  
  102. // Strings
  103. LinkedList<std::string> s(std::cin);
  104. s.print(std::cout) << std::endl;
  105. s.reverse().print(std::cout) << std::endl;
  106. }
Success #stdin #stdout 0s 3464KB
stdin
aaa bbb ccc ddd eee
stdout
5 4 3 2 1 
1 2 3 4 5 
eee ddd ccc bbb aaa 
aaa bbb ccc ddd eee