-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedList.cpp
128 lines (108 loc) · 2 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
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
#include "IList.h"
template <typename Type>
class LinkedList : public ILinkedList {
public:
LinkedList() {
_start = null;
_end = null;
_current = null;
index = 0;
}
void Append(Type item) {
ListItem listItem = new ListItem(item);
if (_start == null) {
_start = listItem;
_end = listItem;
}
else {
_end.Next = listItem;
_end = listItem;
}
}
void Preface(Type item) {
ListItem listItem = new ListItem(item);
if (_start == null) {
_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 != null) {
if (pointer.Item == existingItem.Item) {
listItem.Next = pointer.Next;
pointer.Next = listItem;
return;
}
pointer = pointer.Next;
}
}
void Remove(Type item) {
ListItem pointer = _start;
if (item == _start) {
_start = _start.Next;
}
while (pointer != null) {
if (pointer.Next == item) {
pointer.Next = pointer.Next.Next;
return;
}
pointer = pointer.Next;
}
}
Type Get(int index) {
iterator = 0;
ListItem pointer = _start;
while (pointer != null) {
if (iterator == index) {
return pointer;
}
iterator++;
pointer = pointer.Next;
}
return null;
}
Type Start(){
return _start;
}
Type Tail() {
return _end;
}
Type GetCurrent() {
return _current.Item;
}
void MoveNext() {
_current = _current.Next;
}
void MoveFirst() {
_current = _start;
}
bool AtEnd() {
return _current == _end;
}
private:
ListItem _start;
ListItem _current;
ListItem _end;
int iterator;
};
template <typename Type>
class ListItem {
public:
Type Item;
ListItem Next;
ListItem(Type item) {
Item = item;
Next = null;
}
};