Skip to content

Commit a281216

Browse files
authored
Merge pull request kelvins#260 from ribmarciojr/ribmarciojr/main
Add Stack data structure in C++
2 parents 3df07fe + 28bf41e commit a281216

File tree

2 files changed

+71
-2
lines changed

2 files changed

+71
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -2220,8 +2220,8 @@ In order to achieve greater coverage and encourage more people to contribute to
22202220
</a>
22212221
</td>
22222222
<td> <!-- C++ -->
2223-
<a href="./CONTRIBUTING.md">
2224-
<img align="center" height="25" src="./logos/github.svg" />
2223+
<a href="./src/cpp/Stack.cpp">
2224+
<img align="center" height="25" src="./logos/cplusplus.svg" />
22252225
</a>
22262226
</td>
22272227
<td> <!-- Java -->

src/cpp/Stack.cpp

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <iostream>
2+
3+
// MAX is a macro to define all stack instances size
4+
#define MAX 10
5+
6+
// Stack: Last In - First Out (LIFO)
7+
8+
class Stack {
9+
private:
10+
int array[MAX];
11+
int index = 0;
12+
13+
public:
14+
Stack(){}
15+
16+
void push(int element) {
17+
if (this->index >= MAX) {
18+
throw std::logic_error("Stack is full!");
19+
}
20+
this->array[index] = element;
21+
index++;
22+
}
23+
24+
bool isEmpty() {
25+
if (!this->index) {
26+
return true;
27+
}
28+
return false;
29+
}
30+
31+
int pop() {
32+
if (this->isEmpty()) {
33+
throw std::logic_error("Stack is empty!");
34+
}
35+
index--;
36+
int value = this->array[this->index];
37+
this->array[this->index] = 0;
38+
return value;
39+
}
40+
41+
void print() {
42+
std::cout << "[ ";
43+
for (int i = 0; i < this->index; i++) {
44+
std::cout << this->array[i] << " ";
45+
}
46+
std::cout << "]" << std::endl;
47+
}
48+
};
49+
50+
int main() {
51+
// Create a pointier to a new Stack instance
52+
Stack* stack = new Stack();
53+
54+
std::cout << "Push(1, 2, 4)" << std::endl;
55+
stack->push(1);
56+
stack->push(2);
57+
stack->push(4);
58+
stack->print();
59+
60+
std::cout << "Pop()" << std::endl;
61+
stack->pop();
62+
stack->print();
63+
64+
stack->pop();
65+
stack->pop();
66+
67+
std::cout << "Empty Stack" << std::endl;
68+
stack->print();
69+
}

0 commit comments

Comments
 (0)