forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.cpp
69 lines (56 loc) · 1.34 KB
/
Stack.cpp
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
#include <iostream>
// MAX is a macro to define all stack instances size
#define MAX 10
// Stack: Last In - First Out (LIFO)
class Stack {
private:
int array[MAX];
int index = 0;
public:
Stack(){}
void push(int element) {
if (this->index >= MAX) {
throw std::logic_error("Stack is full!");
}
this->array[index] = element;
index++;
}
bool isEmpty() {
if (!this->index) {
return true;
}
return false;
}
int pop() {
if (this->isEmpty()) {
throw std::logic_error("Stack is empty!");
}
index--;
int value = this->array[this->index];
this->array[this->index] = 0;
return value;
}
void print() {
std::cout << "[ ";
for (int i = 0; i < this->index; i++) {
std::cout << this->array[i] << " ";
}
std::cout << "]" << std::endl;
}
};
int main() {
// Create a pointier to a new Stack instance
Stack* stack = new Stack();
std::cout << "Push(1, 2, 4)" << std::endl;
stack->push(1);
stack->push(2);
stack->push(4);
stack->print();
std::cout << "Pop()" << std::endl;
stack->pop();
stack->print();
stack->pop();
stack->pop();
std::cout << "Empty Stack" << std::endl;
stack->print();
}