-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyStack.hpp
95 lines (77 loc) · 1.34 KB
/
MyStack.hpp
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
#ifndef OOP_PROJECT_MYSTACK_HPP
#define OOP_PROJECT_MYSTACK_HPP
template<typename T>
class MyStack
{
private:
T *data = nullptr;
unsigned long capacity = 1;
unsigned long size = 0;
void inflate();
public:
explicit MyStack(unsigned long size = 0);
~MyStack();
T &top();
void push(const T &item);
void pop();
T &pop_get();
[[nodiscard]] bool empty() const;
};
template<typename T>
T &MyStack<T>::top()
{
return data[size - 1];
}
template<typename T>
void MyStack<T>::push(const T &item)
{
if (size == capacity)
{
this->inflate();
}
data[size++] = item;
}
template<typename T>
void MyStack<T>::pop()
{
size--;
}
template<typename T>
T &MyStack<T>::pop_get()
{
return data[--size];
}
template<typename T>
bool MyStack<T>::empty() const
{
return size == 0;
}
template<typename T>
void MyStack<T>::inflate()
{
capacity *= 2;
T *tmp = new T[capacity]();
for (int i = 0; i < capacity / 2; ++i)
{
tmp[i] = data[i];
}
delete[] data;
data = tmp;
}
template<typename T>
MyStack<T>::MyStack(unsigned long size)
{
this->size = size;
capacity = 1;
while (capacity < size)
{
capacity *= 2;
}
data = new T[capacity]();
}
template<typename T>
MyStack<T>::~MyStack()
{
delete[] data;
}
#endif //OOP_PROJECT_MYSTACK_HPP