-
Notifications
You must be signed in to change notification settings - Fork 32
/
stack_array.h
112 lines (90 loc) · 2.01 KB
/
stack_array.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
108
109
110
111
112
#pragma once
// A Stack class based on an array implementation
// This is a bounded stack (has a fixed size).
template <class T>
class StackArray
{
public:
StackArray(int cap);
StackArray(const StackArray& other);
~StackArray();
void push(const T& val);
T pop();
T top() const;
bool is_empty() const;
bool is_full() const;
void clear();
StackArray& operator=(StackArray other);
private:
T* data;
int capacity;
int last;
};
template <class T>
StackArray<T>::StackArray(int cap)
{
if (cap <= 0)
throw string("ERROR: Invalid capacity!");
capacity = cap;
data = new T[capacity];
last = -1;
}
template <class T>
StackArray<T>& StackArray<T>::operator=(StackArray<T> other) {
swap(data, other.data);
swap(capacity, other.capacity);
swap(last, other.last);
return *this;
}
template <class T>
StackArray<T>::StackArray(const StackArray<T>& other) {
capacity = other.capacity;
data = new T[capacity];
last = other.last;
for (int i = 0; i <= last; i++)
data[i] = other.data[i];
}
template <class T>
StackArray<T>::~StackArray()
{
delete [] data;
}
template <class T>
void StackArray<T>::push(const T& val)
{
if (is_full())
throw string("ERROR: Stack overflow!");
last++;
data[last] = val;
}
template <class T>
T StackArray<T>::pop()
{
if (is_empty())
throw string("ERROR: Stack underflow!");
T val = data[last];
--last;
return val;
}
template <class T>
T StackArray<T>::top() const
{
if (is_empty())
throw string("ERROR: Attempting to retrieve an element from an empty stack!");
return data[last];
}
template <class T>
bool StackArray<T>::is_empty() const
{
return last == -1;
}
template <class T>
bool StackArray<T>::is_full() const
{
return last == capacity - 1;
}
template <class T>
void StackArray<T>::clear()
{
last = -1;
}