aboutsummaryrefslogtreecommitdiff
path: root/list.cpp
blob: b83b018f0121abf44e18fbe881e49cb602e6c128 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* list.cpp
 * Date: 2021-11-20
 * Author: Aryadev Chavali
 */

#include <cstdio>
#include <iostream>
#include <cstdlib>

template <typename T>
struct List
{
  T value;
  struct List<T> *next;

  ~List()
  {
    if (next == nullptr)
      return;
    delete next;
  }
};

template <typename T>
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;
  }

  for (node = lst; node->next != nullptr; node = node->next)
    continue;

  node->next        = new List<T>;
  node->next->value = value;
  node->next->next  = nullptr;
  return lst;
}

/** Reverse a list
 */
template <typename T>
List<T> *reverse(List<T> *lst, List<T> *prev = nullptr)
{
  auto next = lst->next;
  lst->next = prev;
  if (next == nullptr)
    return lst;
  return reverse(next, lst);
}

template <typename T, typename U>
void map(List<T> *lst, U (*f)(T))
{
  if (!lst)
    return;
  lst->value = f(lst->value);
  map(lst->next, f);
}

template <typename T>
T reduce(List<T> *lst, T (*reducer) (T, T), T init = 0)
{
  if (!lst)
    return init;
  if (!init)
    init = lst->value;
  else
    init = reducer(init, lst->value);
  return reduce(lst->next, reducer, init);
}

template <typename T>
std::ostream& operator<<(std::ostream& ostream, const List<T> *lst)
{
  if (!lst)
    return ostream;
  ostream << "|" << lst->value << lst->next;
  return ostream;
}

int main(void)
{
  auto lst = append<int>(nullptr, 1);
  for (int i = 2; i < 10; ++i)
    lst = append(lst, i);
  std::cout << lst << std::endl;
  lst = reverse(lst);
  std::cout << lst << std::endl;
  map<int, int>(lst = reverse(lst), [](int x){ return x * 2; });
  std::cout << lst << std::endl;
  std::cout << reduce<int>(lst, [](int a, int b) { return a + b; }, 0) << std::endl;
  delete lst;
  return 0;
}