File tree 2 files changed +71
-2
lines changed
2 files changed +71
-2
lines changed Original file line number Diff line number Diff line change @@ -2220,8 +2220,8 @@ In order to achieve greater coverage and encourage more people to contribute to
2220
2220
</a>
2221
2221
</td>
2222
2222
<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" />
2225
2225
</a>
2226
2226
</td>
2227
2227
<td> <!-- Java -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments