-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_static_stack.h
108 lines (82 loc) · 1.48 KB
/
template_static_stack.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
#ifndef _STATIC_STACK
#define _STATIC_STACK
#define CAPACITY 4
template<typename T>
class Stack {
private:
T arr[CAPACITY];
size_t top;
void copy(const Stack<T>&);
public:
void empty_stack();
Stack();
Stack(const Stack<T>&);
Stack<T>& operator=(const Stack<T>&);
~Stack();
bool pop();
void push(const T&);
T& peek();
bool is_empty() const;
size_t get_size() const;
};
template<typename T>
void Stack<T>::copy(const Stack<T>& other) {
size_t current = 0;
for (size_t i = 0; i < other.top; ++i) {
arr[current++] = other.arr[i];
}
top = other.top;
}
template<typename T>
void Stack<T>::empty_stack() {
top = 0;
}
template<typename T>
Stack<T>::Stack() :
arr(),
top(0) {}
template<typename T>
Stack<T>::Stack(const Stack<T>& other) {
copy(other);
}
template<typename T>
Stack<T>& Stack<T>::operator=(const Stack<T>& other) {
if (this != &other) {
empty_stack();
copy(other);
}
return *this;
}
template<typename T>
Stack<T>::~Stack() {
empty_stack();
}
template<typename T>
bool Stack<T>::pop() {
if (top == 0)
return false;
else
--top;
return true;
}
template<typename T>
void Stack<T>::push(const T& el) {
if (top >= CAPACITY)
throw "Stack overflow";
arr[top++] = el;
}
template<typename T>
T& Stack<T>::peek() {
if (top == 0)
throw "Invalid index";
return arr[top - 1];
}
template<typename T>
bool Stack<T>::is_empty() const{
return top == 0;
}
template<typename T>
size_t Stack<T>::get_size() const{
return top;
}
#endif // !_STATIC_STACK