-
Notifications
You must be signed in to change notification settings - Fork 0
/
Container.h
160 lines (160 loc) · 2.51 KB
/
Container.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
#pragma once
#include<stddef.h>
#include<string>
template <class T> class Container
{
struct Element
{
Element* next;
Element* previous;
T content;
} *head, *tail,*iter_pointer;
public:
class MyExeption:public std::exception
{
public:
std::string message;
MyExeption(const std::string& msg) noexcept
{
message = msg;
}
};
Container() {};
Container(const Container & other) :
head(NULL),
tail(NULL)
{
for (auto e = other.head; NULL != e; e = e->next) {
AddFirst(e->content);
}
}
void AddFirst(const T& elem)
{
if (head == NULL)
{
Element *NewHead = new Element();
NewHead->content = elem;
NewHead->next = head;
NewHead->previous = NULL;
head = NewHead;
tail = NewHead;
}
else
{
Element *NewHead = new Element();
NewHead->content = elem;
NewHead->next = head;
NewHead->previous = NULL;
head = NewHead;
}
}
void AddLast(const T& elem)
{
if (head != NULL)
{
Element *NewTail = new Element();
tail->next = NewTail;
NewTail->content = elem;
NewTail->next = NULL;
NewTail->previous = tail;
tail = NewTail;
}
else this->AddFirst(elem);
}
void DeleteFirst()
{
if (head == NULL) return;
Element *DelPointer = head;
head = head->next;
if (head != NULL) head->previous = NULL;
delete DelPointer;
}
void DeleteLast()
{
if (head == NULL) return;
if (head->next == NULL)
{
delete head;
head = NULL;
}
else
{
Element* DelPointer = tail;
tail = tail->previous;
tail->next = NULL;
delete DelPointer;
}
}
const T& GetFirst()
{
return head->content;
}
const T& GetLast()
{
return tail->content;
}
void SetToFirst()
{
try
{
this->ExeptionCheck();
}
catch (MyExeption& ex)
{
std::cout << ex.message << "\n";
system("pause");
exit(0);
}
iter_pointer = head;
}
const T* GetAndMove()
{
if (iter_pointer->next != NULL)
{
iter_pointer = iter_pointer->next;
return &iter_pointer->content;
}
else return NULL;
}
void ExeptionCheck()
{
if (this->IsEmpty())
{
throw MyExeption("EmptinessExeption");
}
}
void ExeptionCheck(Element* el)
{
if (el == NULL)
{
throw MyExeption("OutOfRangeExeption");
}
}
bool IsEmpty()
{
if (this->head == NULL) return true;
else return false;
}
int GetNumberOfElements()
{
if (!IsEmpty())
{
Element* Counter = head;
int i = 1;
while (Counter->next)
{
i++;
Counter = Counter->next;
}
return i;
}
else return 0;
}
~Container()
{
while (!IsEmpty())
{
this->DeleteFirst();
}
}
};