-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate_dynamic_stack.h
More file actions
158 lines (109 loc) · 2.28 KB
/
template_dynamic_stack.h
File metadata and controls
158 lines (109 loc) · 2.28 KB
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
#ifndef _DYNAMIC_STACK
#define _DYNAMIC_STACK
template<typename T>
struct node {
T data;
node<T> *prev;
node(const T& _data = T(), node<T>* _prev = nullptr);
};
template<typename T>
node<T>::node(const T& _data = T(), node<T>* _prev = nullptr) :
data(_data),
prev(_prev) {}
template<typename T>
class Stack {
private:
node<T>* top;
size_t size;
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) {
if (other.size == 0) {//if copying from an empty stack
empty_stack();
return;
}
node<T>* current_from = other.top, *current_to;
//initiate top
current_to = top = new node<T>(current_from->data);
current_from = current_from->prev;
while (current_from != nullptr) {
current_to->prev = new node<T>(current_from->data);
current_from = current_from->prev;
current_to = current_to->prev;
}
size = other.size;
}
template<typename T>
void Stack<T>::empty_stack() {
//doing it that way instead of just popping because it
//doesn't waste time for --size and checking if size == 0
node<T>* holder;
while (top != nullptr) {
holder = top;
top = top->prev;
delete holder;
}
size = 0;
}
template<typename T>
Stack<T>::Stack() :
top(nullptr),
size(0) {}
template<typename T>
Stack<T>::Stack(const Stack<T>& other) :
top(nullptr),
size(0){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 (size == 0)
return false;
node<T>* holder = top;
top = top->prev;
delete holder;
--size;
return true;
}
template<typename T>
void Stack<T>::push(const T& el) {
top = new node<T>(el, top);
++size;
}
template<typename T>
T& Stack<T>::peek() {
if (size == 0)
throw "Invalid index";
return top->data;
}
template<typename T>
bool Stack<T>::is_empty() const {
return size == 0;
}
template<typename T>
size_t Stack<T>::get_size() const{
return size;
}
#endif // !_DYNAMIC_STACK