-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.h
166 lines (131 loc) · 2.35 KB
/
LinkedList.h
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#pragma once
template <typename Type>
class ListItem {
public:
Type Item;
ListItem* Next;
ListItem(Type item) {
Item = item;
Next = nullptr;
}
~ListItem() {
delete Next;
}
};
template <typename Type>
class LinkedList {
private:
ListItem<Type>* _start;
ListItem<Type>* _current;
ListItem<Type>* _end;
int iterator;
public:
LinkedList() {
_start = nullptr;
_end = nullptr;
_current = nullptr;
iterator = 0;
}
~LinkedList() {
delete _start;
}
void Append(Type item) {
ListItem<Type>* listItem = new ListItem<Type>(item);
if (_start == nullptr) {
_start = listItem;
_end = listItem;
}
else {
_end->Next = listItem;
_end = listItem;
}
}
void Preface(Type item) {
ListItem<Type>* listItem = new ListItem<Type>(item);
if (_start == nullptr) {
_start = listItem;
_end = listItem;
_current = listItem;
}
else {
listItem->Next = _start;
_start = listItem;
}
}
void AddAfter(Type existingItem, Type newItem) {
ListItem listItem = new ListItem(newItem);
if (existingItem == _end) {
Append(newItem);
return;
}
ListItem pointer = _start;
while (pointer != nullptr) {
if (pointer->Item == existingItem.Item) {
listItem->Next = pointer->Next;
pointer->Next = listItem;
return;
}
pointer = pointer.Next;
}
}
void RemoveLast() {
ListItem<Type>* item = _start;
ListItem<Type>* prevItem = _start;
if (_start == nullptr) {
return;
}
if (_start == _end) {
_start = nullptr;
_end = nullptr;
_current = nullptr;
}
while (item->Next != nullptr) {
prevItem = item;
item = item->Next;
}
prevItem->Next = nullptr;
_end = prevItem;
}
Type Get(int index) {
iterator = 0;
ListItem pointer = _start;
while (pointer != nullptr) {
if (iterator == index) {
return pointer;
}
iterator++;
pointer = pointer.Next;
}
return nullptr;
}
Type First() {
return _start->Item;
}
Type Last() {
return _end->Item;
}
Type GetCurrent() {
return _current->Item;
}
void MoveNext() {
_current = _current->Next;
}
void MoveFirst() {
_current = _start;
}
bool AtEnd() {
return _current == nullptr;
}
int Length() {
int counter = 0;
ListItem<Type>* item = _start;
while (item != nullptr) {
counter++;
item = item->Next;
}
return counter;
}
bool IsEmpty() {
return _start == nullptr;
}
};