Repository navigation
Expand file tree
/
Copy pathstack.hpp
More file actions
76 lines (60 loc) · 1.65 KB
/
Copy pathstack.hpp
File metadata and controls
76 lines (60 loc) · 1.65 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
#ifndef STACK_H
#define STACK_H
#include <cinttypes>
#include <stdexcept>
#include <iostream>
namespace mystack {
template <typename T>
class Stack {
public:
// Constructors
Stack(): _size(0), _capacity(1) {
this->_arr = new T[_capacity];
this->_arr[0] = T{};
}
Stack(const Stack& s): _size(s.size()), _capacity(s.capacity()) {
this->_arr = *s.arr();
}
Stack(const Stack* s): _size(s.size()), _capacity(s.capacity()) {
this->_arr = s._arr;
}
// Get
uint64_t size() {
return this->_size;
}
uint64_t capacity() {
return this->_capacity;
}
T pop() {
if (this->_size == 0) {
throw std::underflow_error("Stack is empty!\n");
}
this->_size--;
return this->_arr[this->_size];
}
// Set
void push(T e) {
if (this->_size + 1 > this->_capacity) {
this->resize(2 * this->_capacity);
}
this->_arr[this->_size] = e;
this->_size++;
this->_arr[this->_size] = T{};
}
void resize(uint64_t new_capacity) {
this->_capacity = new_capacity;
this->_arr = (T*) realloc(this->_arr, new_capacity * sizeof(T));
}
// Destructor
~Stack() {
this->_size = 0;
this->_capacity = 0;
delete[] this->_arr;
}
private:
uint64_t _size;
uint64_t _capacity;
T* _arr;
}; // end of Stack class
}; // end of mystack namespace
#endif