From e7e819e1ddfb13a7a650d5e211e145bf7f11e3fa Mon Sep 17 00:00:00 2001 From: Aryadev Chavali Date: Sun, 9 Jul 2023 16:27:37 +0100 Subject: (list)+constructor for List, ~cleaned up some code Same argument as btree --- list.cpp | 57 +++++++++++++++++++++++++-------------------------------- 1 file changed, 25 insertions(+), 32 deletions(-) (limited to 'list.cpp') diff --git a/list.cpp b/list.cpp index aa04294..b87a3e2 100644 --- a/list.cpp +++ b/list.cpp @@ -11,7 +11,13 @@ template struct List { T value; - struct List *next; + List *next; + + List(T val, List *n) + { + value = val; + next = n; + } ~List() { @@ -26,19 +32,12 @@ List *append(List *lst, T value) { List *node; if (lst == nullptr) - { - node = new List; - node->value = value; - node->next = nullptr; - return node; - } + return new List(value, nullptr); for (node = lst; node->next != nullptr; node = node->next) continue; - node->next = new List; - node->next->value = value; - node->next->next = nullptr; + node->next = new List(value, nullptr); return lst; } @@ -55,12 +54,11 @@ List *reverse(List *lst, List *prev = nullptr) } template -void map(List *lst, U (*f)(T)) +List *map(List *lst, U (*f)(T)) { if (!lst) - return; - lst->value = f(lst->value); - map(lst->next, f); + return nullptr; + return new List(f(lst->value), map(lst->next, f)); } template @@ -68,7 +66,7 @@ T reduce(List *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(lst = reverse(lst), - [](int x) - { - return x * 2; - }); - std::cout << lst << std::endl; - puts("Reverse map..."); - map(lst, - [](int x) - { - return x / 2; - }); + auto mapped = map(lst = reverse(lst), + [](int x) + { + return x * 2; + }); + std::cout << mapped << std::endl; + delete mapped; printf("Sum all numbers in list: "); std::cout << reduce( - 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: "); -- cgit v1.2.3-13-gbd6f