-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuptr_list.hpp
70 lines (59 loc) · 1.06 KB
/
uptr_list.hpp
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
// This file is covered by the LICENSE file in the root of this project.
#pragma once
#include "io.hpp"
#include <cstddef>
#include <memory>
#include <utility>
template<typename T>
struct Node;
template<typename T>
using Node_ptr = std::unique_ptr<Node<T>>;
template<typename T>
struct Node
{
const T data;
Node_ptr<T> next;
explicit Node(T data) : data(std::move(data))
{}
};
template<typename T>
void read_list(std::size_t size, Node_ptr<T>& list)
{
list.reset();
Node<T>* tail;
while (size-- > 0)
{
T data;
read(data);
if (list)
{
tail->next = std::make_unique<Node<T>>(std::move(data));
tail = tail->next.get();
}
else
{
list = std::make_unique<Node<T>>(std::move(data));
tail = list.get();
}
}
}
template<typename T>
void read_list(Node_ptr<T>& list)
{
std::size_t size;
read(size);
read_list(size, list);
}
template<typename T>
void write(const Node_ptr<T>& head)
{
if (!head)
return;
write(head->data);
auto node = head->next.get();
while (node != nullptr)
{
write(' ', node->data);
node = node->next.get();
}
}