-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathStack.cpp
82 lines (67 loc) · 1.66 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
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
//MAX is a macro to define all stack instances size
#define MAX 10
#define TYPE_SIZE 4
// Stack: Fist in - Last Out
class Stack{
private:
int arr[MAX];
int elements{0};
public:
Stack(){}
bool insert(int element){
if((this->elements * TYPE_SIZE) == sizeof(this->arr)){
return false;
};
this->arr[elements] = element;
elements++;
return true;
}
bool isEmpty(){
if(!this->elements){
return true;
}
return false;
}
bool remove(){
if(this->isEmpty()){
return false;
}
this->arr[this->elements - 1] = 0;
elements--;
return true;
}
int top(){
if(this->isEmpty()){
return -1;
}
return this->arr[this->elements - 1];
}
int getSize(){
return sizeof(this->arr) / TYPE_SIZE;
}
};
int main(){
//Create a pointier to a new Stack instance
Stack* stack = new Stack();
//Insert Elements, then removes
stack->insert(1);
stack->insert(2);
stack->insert(4);
std:: cout << stack->top() << std::endl;
stack->remove();
std:: cout << stack->top() << std::endl;
stack->remove();
stack->remove();
std::cout << "--------------------" << "\n";
//Try to insert beyond max size
for(int i = 0; i < 15; i++){
std::cout << stack->insert(i) << std::endl;
}
std::cout << "--------------------" << "\n";
// Show and remove stack top element
for(int i = 0; i < stack->getSize(); i++){
std::cout << stack->top() << std::endl;
stack->remove();
}
}