-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslist_lib.cc
114 lines (99 loc) · 2.31 KB
/
slist_lib.cc
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "slist.hh"
#include <cstring>
#include <iostream>
using namespace std;
namespace slist {
SingleLinkList::SingleLinkList(const char *s) {
size_t len = strlen(s);
if (0u == len) {
cerr << "Provide at least one character to create a list." << endl;
} else {
int i = static_cast<int>(len);
while (i > 0) {
unique_ptr<slistelem> elem{(new slistelem(s[i - 1]))};
elem->next = move(h_);
h_ = move(elem);
i--;
}
}
}
size_t SingleLinkList::Count(char c) const {
slistelem *cursor = first();
size_t result = 0u;
while (cursor) {
if (c == cursor->data) {
result++;
}
cursor = cursor->next.get();
}
return result;
}
size_t SingleLinkList::Length() const {
size_t len = 0u;
slistelem *cursor = first();
while (cursor) {
len++;
cursor = cursor->next.get();
}
return len;
}
void SingleLinkList::Prepend(char c) {
unique_ptr<slistelem> temp{new slistelem(c)};
temp->next = move(h_);
h_ = move(temp);
}
slistelem *SingleLinkList::Tail() const {
slistelem *save = nullptr, *tail = h_.get();
while (tail) {
save = tail;
tail = tail->next.get();
}
return save;
}
void SingleLinkList::Append(SingleLinkList &&sll) {
if (sll.empty()) {
return;
}
slistelem *tail = Tail();
while (sll.first()) {
unique_ptr<slistelem> elem{new slistelem(sll.first()->data)};
sll.Delete();
tail->next = move(elem);
tail = tail->next.get();
}
}
void SingleLinkList::Delete() {
if (!h_) {
return;
}
unique_ptr<slistelem> temp = move(h_);
h_ = move(temp->next);
temp.reset();
}
ostream &operator<<(ostream &out, const SingleLinkList &sll) {
slistelem *cursor = sll.first();
while (cursor) {
out << cursor->data << " -> ";
cursor = cursor->next.get();
}
out << "0" << endl;
return out;
}
// Tail-recursive version not obviously simpler than the while-loop version.
// Not possible to make this function an extraction operator since it does not
// need an object parameter and cannot return an ostream reference.
void SingleLinkList::Print(slistelem *cursor) const {
if (!cursor) {
cout << "0" << endl;
return;
}
cout << cursor->data << " -> ";
Print(cursor->next.get());
}
// Stack interface
char SingleLinkList::Pop() {
char ret = first()->data;
Delete();
return ret;
}
} // namespace slist