-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingly_linked_list.cpp
More file actions
67 lines (53 loc) · 1.25 KB
/
singly_linked_list.cpp
File metadata and controls
67 lines (53 loc) · 1.25 KB
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
#include <iostream>
template <typename T> class SinglyLinkedList {
private:
struct Node {
T data;
Node *next{nullptr};
};
Node *m_head{nullptr};
Node *m_tail{nullptr};
public:
SinglyLinkedList();
~SinglyLinkedList();
void append(const T &);
Node *head();
Node *tail();
};
template <typename T> SinglyLinkedList<T>::SinglyLinkedList() {}
template <typename T> SinglyLinkedList<T>::~SinglyLinkedList() {
Node *current = m_head;
while (current) {
Node *next = current->next;
delete current;
current = next;
}
std::cout << "List destroyed" << std::endl;
}
template <typename T> void SinglyLinkedList<T>::append(const T &data) {
Node *node = new Node{data, nullptr};
if (m_tail) {
m_tail->next = node;
m_tail = node;
} else {
m_head = m_tail = node;
}
}
template <typename T>
typename SinglyLinkedList<T>::Node *SinglyLinkedList<T>::head() {
return m_head;
}
template <typename T>
typename SinglyLinkedList<T>::Node *SinglyLinkedList<T>::tail() {
return m_tail;
}
int main() {
SinglyLinkedList<char> list;
list.append('l');
list.append('e');
list.append('e');
list.append('t');
std::cout << list.head()->data << std::endl;
std::cout << list.tail()->data << std::endl;
return 0;
}