fork download
  1. #include <iostream>
  2.  
  3. template <class T>
  4. class Node {
  5. public:
  6. T value;
  7. Node<T>* next;
  8. Node(T value_, Node<T>* next_) : value(value_), next(next_) {}
  9. Node(T value_) : value(value_), next(NULL) {}
  10. };
  11.  
  12.  
  13.  
  14. using namespace std;
  15.  
  16. template <class T>
  17. class List {
  18. public:
  19. List() : head(NULL) {}
  20.  
  21. void prepend(T val) {
  22. Node<T>* node_ptr = new Node<T>(val, head);
  23. head = node_ptr;
  24. }
  25.  
  26. void print() {
  27. cout << "[";
  28. _node_loop(_print_node);
  29. cout << "]" << endl;
  30. }
  31.  
  32. ~List() {
  33. _node_loop(_del_node);
  34. }
  35.  
  36. static List<T> from_array(T tarray[], int N) {
  37. List<T> ls = List<T>();
  38. for (int i = 0; i < N; i++) {
  39. ls.prepend(tarray[i]);
  40. }
  41. return ls;
  42. }
  43.  
  44. private:
  45. Node<T>* head;
  46.  
  47. void _node_loop(void (*kernel)(Node<T>*)) {
  48. Node<T>* node_ptr = head;
  49. Node<T>* tmp;
  50. while (node_ptr != NULL) {
  51. tmp = node_ptr;
  52. node_ptr = node_ptr->next;
  53. kernel(tmp);
  54. }
  55. }
  56.  
  57. static void _print_node(Node<T>* node_ptr) {
  58. if (node_ptr->next == NULL) {
  59. cout << node_ptr->value;
  60. }
  61. else {
  62. cout << node_ptr->value << ", ";
  63. }
  64. }
  65.  
  66. static void _del_node(Node<T>* node_ptr) {
  67. delete node_ptr;
  68. }
  69. };
  70.  
  71.  
  72.  
  73. int main() {
  74. int my_array[] = {1, 2, 3, 4, 5};
  75. List<int> my_list = List<int>::from_array(my_array, 5);
  76. my_list.print();
  77. return 0;
  78. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
[5, 4, 3, 2, 1]