(list)+constructor for List, ~cleaned up some code

Same argument as btree
This commit is contained in:
2023-07-09 16:27:37 +01:00
parent 5c928bc8c7
commit e7e819e1dd

View File

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