diff options
-rw-r--r-- | list.cpp | 57 |
1 files changed, 25 insertions, 32 deletions
@@ -11,7 +11,13 @@ template <typename T> struct List { T value; - struct List<T> *next; + List<T> *next; + + List(T val, List<T> *n) + { + value = val; + next = n; + } ~List() { @@ -26,19 +32,12 @@ List<T> *append(List<T> *lst, T value) { List<T> *node; if (lst == nullptr) - { - node = new List<T>; - node->value = value; - node->next = nullptr; - return node; - } + return new List<T>(value, nullptr); for (node = lst; node->next != nullptr; node = node->next) continue; - node->next = new List<T>; - node->next->value = value; - node->next->next = nullptr; + node->next = new List<T>(value, nullptr); return lst; } @@ -55,12 +54,11 @@ List<T> *reverse(List<T> *lst, List<T> *prev = nullptr) } template <typename T, typename U> -void map(List<T> *lst, U (*f)(T)) +List<U> *map(List<T> *lst, U (*f)(T)) { if (!lst) - return; - lst->value = f(lst->value); - map(lst->next, f); + return nullptr; + return new List<U>(f(lst->value), map(lst->next, f)); } template <typename T> @@ -68,7 +66,7 @@ T reduce(List<T> *lst, T (*reducer)(T, T), T init = 0) { if (!lst) return init; - if (!init) + else if (!init) init = lst->value; else init = reducer(init, lst->value); @@ -107,25 +105,20 @@ int main(void) std::cout << lst << std::endl; puts("Reverse list again..."); printf("Map list with f(x) = 2x: "); - map<int, int>(lst = reverse(lst), - [](int x) - { - return x * 2; - }); - std::cout << lst << std::endl; - puts("Reverse map..."); - map<int, int>(lst, - [](int x) - { - return x / 2; - }); + auto mapped = map<int, int>(lst = reverse(lst), + [](int x) + { + return x * 2; + }); + std::cout << mapped << std::endl; + delete mapped; printf("Sum all numbers in list: "); std::cout << reduce<int>( - lst, - [](int a, int b) - { - return a + b; - }, + lst, + [](int a, int b) + { + return a + b; + }, 0) << std::endl; printf("Print all even numbers 1..10: "); |