-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSinglyLinkedList.cpp
More file actions
81 lines (80 loc) · 1.61 KB
/
SinglyLinkedList.cpp
File metadata and controls
81 lines (80 loc) · 1.61 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
using namespace std;
template <class T> struct Node {
T data;
explicit Node(T d = 0) : data(d) {}
Node *next = nullptr;
~Node() { delete next; }
// TODO: write copy ctor, move ctor, copy assignment operator, move assignment
// operator
};
template <class T> class LinkedList {
private:
Node<T> head;
size_t size = 0;
public:
void insert(T d) {
Node<T> *n = new Node<T>(d);
Node<T> *curr = &head;
++size;
int i = 0;
while (i < (size - 1)) {
curr = curr->next;
++i;
}
curr->next = n;
}
void insert(T d, int idx) {
if (idx < 0 || idx > size)
return;
if (idx == size)
insert(d);
else {
Node<T> *n = new Node<T>(d);
Node<T> *curr = &head;
++size;
int i = 0;
while (i < idx) {
curr = curr->next;
++i;
}
n->next = curr->next;
curr->next = n;
}
}
void remove(int idx) {
if (idx < 0 || idx >= size)
return;
Node<T> *curr = &head;
--size;
int i = 0;
while (i < idx) {
curr = curr->next;
++i;
}
curr->next = curr->next->next;
}
T operator[](int idx) {
if (idx < 0 || idx >= size)
return 0;
Node<T> *curr = &head;
int i = 0;
while (i <= idx) {
curr = curr->next;
++i;
}
return curr->data;
}
bool is_empty() { return size == 0; }
int length() { return size; }
T front() { return (*this)[0]; }
T back() { return (*this)[size - 1]; }
};
int main() {
LinkedList<float> ll;
ll.insert(1.6);
for (int i = 0; i < ll.length(); ++i) {
cout << ll[i] << ' ';
}
return 0;
}