-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweek14-final.cpp
88 lines (76 loc) · 2.02 KB
/
week14-final.cpp
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
#include <iostream>
template<typename T>
struct Node
{
Node<T>* next;
T value;
Node(const T& value) : next{nullptr}, value{value} { }
};
template<typename T>
struct List
{
Node<T>* head;
List() : head{} { }
List(const List<T>& other) : head{new Node<T>(other.head->value)}
{
auto* node_ptr = other.head->next;
while(node_ptr)
{
push_back(node_ptr->value);
node_ptr = node_ptr->next;
}
}
// returns a pointer to the last node of the list
Node<T>* get_tail()
{
auto* node_ptr = head;
while(node_ptr && node_ptr->next)
node_ptr = node_ptr->next;
return node_ptr;
}
// insert a node allocated from the heap, storing "value",
// to the beginning of the list
void push_front(const T& value)
{
auto* new_node = new Node<T>(value);
new_node->next = head;
head = new_node;
}
// insert a node allocated from the heap, storing "value",
// to the end of the list
void push_back(const T& value)
{
auto* new_node = new Node<T>(value);
auto* tail = get_tail();
if(tail)
tail->next = new_node;
else
head = new_node;
}
};
template<typename KeyType, typename ValueType>
struct Pair
{
KeyType key;
ValueType value;
};
int main(int argc, char* argv[])
{
auto ints = List<int>{};
ints.push_back(10);
ints.push_back(20);
for(auto* ptr=ints.head; ptr != nullptr; ptr=ptr->next)
std::cout << ptr->value << std::endl;
auto math_values = List<Pair<double, const char*>>{};
math_values.push_back({3.14159, "Pi"});
math_values.push_back({2.71828, "Euler Number"});
math_values.push_back({2.61803, "Phi (GoldenRatio)"});
for(auto* ptr=math_values.head; ptr != nullptr; ptr=ptr->next)
std::cout << ptr->value.key << ", " << ptr->value.value << std::endl;
// 10
// 20
// 3.14159, Pi
// 2.71828, Euler Number
// 2.61803, Phi (GoldenRatio)
return 0;
}