Skip to content

Commit bd9d7a8

Browse files
committed
feat: add stack data structure
1 parent 3df07fe commit bd9d7a8

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

src/cpp/Stack.cpp

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include <iostream>
2+
//MAX is a macro to define all stack instances size
3+
#define MAX 10
4+
#define TYPE_SIZE 4
5+
6+
// Stack: Fist in - Last Out
7+
8+
class Stack{
9+
private:
10+
int arr[MAX];
11+
int elements{0};
12+
13+
public:
14+
Stack(){}
15+
16+
bool insert(int element){
17+
if((this->elements * TYPE_SIZE) == sizeof(this->arr)){
18+
return false;
19+
};
20+
this->arr[elements] = element;
21+
elements++;
22+
return true;
23+
}
24+
25+
bool isEmpty(){
26+
if(!this->elements){
27+
return true;
28+
}
29+
return false;
30+
}
31+
32+
bool remove(){
33+
if(this->isEmpty()){
34+
return false;
35+
}
36+
this->arr[this->elements - 1] = 0;
37+
elements--;
38+
return true;
39+
}
40+
41+
int top(){
42+
if(this->isEmpty()){
43+
return -1;
44+
}
45+
return this->arr[this->elements - 1];
46+
}
47+
48+
int getSize(){
49+
return sizeof(this->arr) / TYPE_SIZE;
50+
}
51+
};
52+
int main(){
53+
//Create a pointier to a new Stack instance
54+
Stack* stack = new Stack();
55+
56+
//Insert Elements, then removes
57+
stack->insert(1);
58+
stack->insert(2);
59+
stack->insert(4);
60+
std:: cout << stack->top() << std::endl;
61+
stack->remove();
62+
std:: cout << stack->top() << std::endl;
63+
stack->remove();
64+
stack->remove();
65+
66+
std::cout << "--------------------" << "\n";
67+
68+
//Try to insert beyond max size
69+
for(int i = 0; i < 15; i++){
70+
std::cout << stack->insert(i) << std::endl;
71+
}
72+
73+
std::cout << "--------------------" << "\n";
74+
75+
// Show and remove stack top element
76+
for(int i = 0; i < stack->getSize(); i++){
77+
std::cout << stack->top() << std::endl;
78+
stack->remove();
79+
80+
}
81+
82+
}

0 commit comments

Comments
 (0)