Files
algorithms/list.cpp
Aryadev Chavali e30444cdde (list)+destructor function in struct
Nice feature of C++, destructors make it kinda nice to do memory
management. Though they don't fully reduce the pain lol
2021-11-20 22:57:27 +00:00

62 lines
1009 B
C++

/* 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 == NULL)
return;
delete next;
}
};
template <typename T>
List<T> *append(List<T> *lst, T value)
{
List<T> *node;
if (lst == NULL)
{
node = new List<T>;
node->value = value;
node->next = NULL;
return node;
}
for (node = lst; node->next != NULL; node = node->next)
continue;
node->next = new List<T>;
node->next->value = value;
node->next->next = NULL;
return lst;
}
template <typename T>
std::ostream& operator<<(std::ostream& ostream, const List<T> *lst)
{
if (lst == NULL)
return ostream;
ostream << "|" << lst->value << lst->next;
return ostream;
}
int main(void)
{
auto lst = append<int>(NULL, 1);
for (int i = 2; i < 10; ++i)
lst = append(lst, i);
std::cout << lst << std::endl;
return 0;
}