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. void 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. void LinkedList<T>::reverse()
  66. {
  67. node *prev = nullptr;
  68. node *next = nullptr;
  69. if (!head) return;
  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. }
  79.  
  80. template <class T>
  81. std::ostream& LinkedList<T>::print(std::ostream &os)
  82. {
  83. node *iter = head;
  84. while (iter)
  85. {
  86. os << iter->data << " ";
  87. iter = iter->next;
  88. }
  89. return os;
  90. }
  91.  
  92.  
  93. int main()
  94. {
  95. // Integers
  96. LinkedList<int> list({1, 2, 3, 4, 5});
  97. list.print(std::cout) << std::endl;
  98. list.reverse();
  99. list.print(std::cout) << std::endl;
  100.  
  101. // Strings
  102. LinkedList<std::string> s(std::cin);
  103. s.print(std::cout) << std::endl;
  104. s.reverse();
  105. s.print(std::cout) << std::endl;
  106. }
Success #stdin #stdout 0s 3468KB
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