-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.h
164 lines (137 loc) · 2.67 KB
/
list.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
#ifndef ALGORITHMS_LIST_H_
#define ALGORITHMS_LIST_H_
#include <iostream>
template <class O>
class list_object {
public:
list_object<O>();
O data;
list_object* next;
list_object<O> operator++();
};
template <class O>
inline list_object<O> list_object<O>::operator++() {
data = next->data;
next = next->next;
return *this;
}
template <class O>
inline list_object<O>::list_object()
{
}
template <class T>
class list {
public:
int push_back(T element);
T pop_front();
T peek_front();
void insert(T element, int index);
void delete_index(int index);
int search(T target);
void clear();
int size() { return count; }
list<T>();
~list<T>();
private:
list_object<T>* skip2index(int index);
int count;
list_object<T> *head;
list_object<T> *tail;
};
template <class T>
list<T>::list()
:count(0), head(NULL), tail(NULL)
{
}
template <class T>
list<T>::~list() {
clear();
}
template <class T>
void list<T>::clear() {
while (count > 0) {
pop_front();
}
}
template <class T>
int list<T>::push_back(T data) {
list_object<T> *elem = new list_object<T>();
elem->data = data;
if (0 == count) {
head = elem;
tail = elem;
}
else {
tail->next = elem;
tail = elem;
}
return ++count;
}
template <class T>
T list<T>::pop_front() {
if (count > 0) {
list_object<T> *temp = head;
head = head->next;
T data = temp->data;
delete temp;
--count;
return data;
}
else {
return -1;
}
}
template <class T>
T list<T>::peek_front() {
return count <= 0 ? nullptr : head;
}
template <class T>
void list<T>::delete_index(int index) {
if (index < count)
{
list_object<T> *obj = skip2index(--index);
if (obj != nullptr)
{
list_object<T> *del = obj->next;
obj = del->next;
delete del;
}
}
}
template <class T>
void list<T>::insert(T element, int index) {
list_object<T> *elem = new list_object<T>();
}
template <class T>
int list<T>::search(T target) {
if (0 == count) {
return -1;
}
list_object<T> *elem = head;
int i = 0;
while (elem->next != NULL) {
if (elem->data == target) {
return i;
}
elem = elem->next;
++i;
}
return -1;
}
template <class T>
list_object<T>* list<T>::skip2index(int index) {
if (index >= count)
{
return nullptr;
}
else
{
list_object<T> *obj = head;
for (int i = 0; i < index; ++i)
{
++obj;
}
return obj;
}
}
#endif ALGORITHMS_LIST_H_