-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array
166 lines (164 loc) · 2.33 KB
/
Array
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
#include<iostream>
template <class T>
class MyList
{
struct Node
{
T data;
Node* next;
Node* prev;
Node(const T& data_, Node* next_ = nullptr, Node* prev_ = nullptr) :data{ data_ }, next{ next_ }, prev{ prev_ }{};
};
Node* getNode(size_t idx)
{
Node* curr;
size_t cnt{ 0 };
if (idx > (size - 1) / 2)
{
for (curr = tail, cnt = size; cnt > idx; curr = curr->prev, --cnt);
}
else
{
for (curr = head; cnt < idx; curr = curr->next, ++cnt);
}
return curr;
}
size_t size;
Node* head, * tail;
public:
MyList() :head{ nullptr }, tail{ nullptr }, size{ 0 }{};
size_t getSize() { return size; }
void push_back(const T& data_)
{
if (!head)
{
tail = head = new Node{ data_ };
}
else
{
tail->next = new Node{ data_, nullptr, tail };
}
++size;
}
void push_front(const T& data_)
{
if (!head)
{
tail = head = new Node{ data_ };
}
else
{
head->prew = new Node{ data_,head, };
head = head->prew;
}
++size;
}
void pop_front()
{
if (head)
{
head->next->prew = nullptr;
}
Node tmp{ head->next };
delete head;
head = tmp;
--size;
if (!head)
{
tail = head;
}
}
void pop_back()
{
if (tail)
{
if (tail->prev)
{
tail->prev->next = nullptr;
}
}
Node* tmp{ tail->prev };
delete tail;
tail = tmp;
--size;
if (!tail)
{
head = tail;
}
}
T& operator [](size_t idx) { return getNode(idx)->data; }
void insertAt(size_t idx, const T& data_)
{
Node* curr{ getNode(idx) };
if (size == 1)
{
push_back(data_);
return;
}
Node* newNode = new Node{ data_,curr->next,curr };
curr->next = newNode;
newNode->next->prev = newNode;
++size;
}
void deleteAt(size_t idx)
{
Node* curr{ getNode(idx) };
if (size == 1)
{
head = tail = nullptr;
size = 0;
return;
}
if (curr->prev)
{
curr->prev->next = curr->next;
}
else
{
head = curr->next;
}
if (curr->next)
{
curr->next->prev = curr->prev;
}
else
{
tail = curr->prev;
}
--size;
delete curr;
}
Node* getHead()
{
return head;
}
Node* getTail()
{
return tail;
}
};
template<class T>
class Array
{
MyList<T> arr;
public:
int getSize()
{
return arr.getSize();
}
bool isEmpty()
{
return arr.getSize;
}
void add(const T& data)
{
arr.push_back(data);
}
T operator [](size_t idx)
{
return arr[idx];
}
};
int main()
{
}