grokk-exs/4.3/iterate_max.cpp

60 lines
1.7 KiB
C++

#include <iostream>
#include <memory>
#include <limits>
template <typename T>
struct Node
{
T value;
std::unique_ptr<Node<T>> next;
};
template <typename T>
T max(const std::unique_ptr<Node<T>>& node, T max_value)
{
if (!node)
return max_value;
return max(node->next, (node->value > max_value)
? node->value
: max_value);
}
int main()
{
{
using NodeT = Node<std::string>;
auto head = std::make_unique<NodeT>(NodeT{"JKFHDJKSFHaaaaaaaaaaJKSFHKJSDJFSDKH", nullptr});
head->next = std::make_unique<NodeT>(NodeT{"12", nullptr});
head->next->next = std::make_unique<NodeT>(NodeT{"35", nullptr});
head->next->next->next = std::make_unique<NodeT>(NodeT{"JKFHDJKSFHKJSDJFSDKH", nullptr});
std::cout << "Size 1: " << max(head, std::string{}) << '\n';
}
{
using NodeT = Node<int>;
auto head = std::make_unique<NodeT>(NodeT{1, nullptr});
head->next = std::make_unique<NodeT>(NodeT{34, nullptr});
head->next->next = std::make_unique<NodeT>(NodeT{12, nullptr});
head->next->next->next = std::make_unique<NodeT>(NodeT{-4534, nullptr});
head->next->next->next->next = std::make_unique<NodeT>(NodeT{std::numeric_limits<int>::max(), nullptr});
std::cout << "Size 2: " << max(head, std::numeric_limits<int>::min()) << '\n';
}
{
using NodeT = Node<char>;
auto head = std::make_unique<NodeT>(NodeT{'#', nullptr});
std::cout << "Size 3: " << max(head, std::numeric_limits<char>::min()) << '\n';
}
{
std::cout << "Size empty: " << max(std::unique_ptr<Node<double>>(), std::numeric_limits<double>::min()) << '\n';
}
}