Skip to content

Commit 331fa30

Browse files
authored
Merge pull request kelvins#240 from Riei-Joaquim/feat/stack
Feat/stack
2 parents a156662 + c999106 commit 331fa30

File tree

2 files changed

+92
-2
lines changed

2 files changed

+92
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -2278,8 +2278,8 @@ In order to achieve greater coverage and encourage more people to contribute to
22782278
</a>
22792279
</td>
22802280
<td> <!-- C++ -->
2281-
<a href="./CONTRIBUTING.md">
2282-
<img align="center" height="25" src="./logos/github.svg" />
2281+
<a href="./src/cpp/DynamicStack.cpp">
2282+
<img align="center" height="25" src="./logos/cplusplus.svg" />
22832283
</a>
22842284
</td>
22852285
<td> <!-- Java -->

src/cpp/DynamicStack.cpp

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#include <iostream>
2+
3+
class Stack {
4+
struct node {
5+
int data;
6+
node *next;
7+
};
8+
node *head = nullptr;
9+
10+
public:
11+
static constexpr int emptyStack = -1;
12+
13+
void push(int value) {
14+
node *newNode;
15+
newNode = new node;
16+
newNode->data = value;
17+
18+
if (head == nullptr) {
19+
newNode->next = nullptr;
20+
} else {
21+
newNode->next = head;
22+
}
23+
head = newNode;
24+
}
25+
26+
bool isEmpty() {
27+
return head == nullptr;
28+
}
29+
30+
int pop() {
31+
int value = emptyStack;
32+
if (!isEmpty()) {
33+
value = head->data;
34+
node *next, *at;
35+
next = head->next;
36+
at = head;
37+
head = next;
38+
delete at;
39+
}
40+
return value;
41+
}
42+
43+
int showTop() {
44+
int value = emptyStack;
45+
if (!isEmpty()) {
46+
value = head->data;
47+
}
48+
return value;
49+
}
50+
51+
int size() {
52+
int counter = 0;
53+
node *temp;
54+
temp = head;
55+
while (temp->next != nullptr) {
56+
counter++;
57+
temp = temp->next;
58+
}
59+
counter++;
60+
return counter;
61+
}
62+
};
63+
64+
int main() {
65+
Stack stack;
66+
int value;
67+
68+
for (int i = 0; i < 10; i++) {
69+
std::cout << "Push: " << i + 1 << std::endl;
70+
stack.push(i + 1);
71+
}
72+
73+
for (int i = 0; i < 12; i++) {
74+
value = stack.pop();
75+
if (value != Stack::emptyStack) {
76+
std::cout << "Pop: " << value << std::endl;
77+
} else {
78+
std::cout << "Stack is empty!" << std::endl;
79+
}
80+
}
81+
82+
for (int i = 0; i < 5; i++) {
83+
std::cout << "Push: " << i + 1 << std::endl;
84+
stack.push(i + 1);
85+
}
86+
87+
std::cout << "Stack have " << stack.size() << " elements" << std::endl;
88+
std::cout << stack.showTop() << " is the top element of stack" << std::endl;
89+
return 0;
90+
}

0 commit comments

Comments
 (0)