-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.cpp
78 lines (66 loc) · 1.4 KB
/
LinkedList.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
#include <iostream>
#include <memory>
struct Node
{
int data;
std::unique_ptr<Node> next;
~Node() {
std::cout << "Data: " << this->data << " destroyed\n";
}
};
struct List
{
std::unique_ptr<Node> head;
~List()
{
// destroy list nodes sequentially in a loop, the default destructor
// would have invoked its `next`'s destructor recursively, which would
// cause stack overflow for sufficiently large lists.
while (head)
head = std::move(head->next);
}
void push(int data)
{
head = std::unique_ptr<Node>(new Node{data, std::move(head)});
}
void print() {
Node* curr = head.get();
while (curr) {
std::cout << curr->data << " ";
curr = curr->next.get();
}
std::cout << "\n";
}
void reverse() { // Nice task.
std::unique_ptr<Node>prev = nullptr;
std::unique_ptr<Node>curr = std::move(head);
while (curr) {
head = std::move(curr->next);
curr->next = std::move(prev);
prev = std::move(curr);
curr = std::move(head);
}
head = std::move(prev);
}
friend std::ostream& operator<<(std::ostream& os, const List &list);
};
std::ostream& operator<< (std::ostream& os, const List &list) {
Node* curr = list.head.get();
while (curr) {
os << curr->data << " ";
curr = curr->next.get();
}
os << "\n";
return os;
}
int main() {
{
List wall;
for (int i = 0; i < 10; i++) {
wall.push(i);
}
std::cout << wall;
wall.reverse();
std::cout << wall;
}
}