Skip to content

Commit 28bf41e

Browse files
authored
Update Stack.cpp
1 parent 24e8c40 commit 28bf41e

File tree

1 file changed

+28
-41
lines changed

1 file changed

+28
-41
lines changed

Diff for: src/cpp/Stack.cpp

+28-41
Original file line numberDiff line numberDiff line change
@@ -2,81 +2,68 @@
22

33
// MAX is a macro to define all stack instances size
44
#define MAX 10
5-
#define TYPE_SIZE 4
65

76
// Stack: Last In - First Out (LIFO)
87

98
class Stack {
109
private:
11-
int arr[MAX];
12-
int elements{0};
10+
int array[MAX];
11+
int index = 0;
1312

1413
public:
1514
Stack(){}
1615

17-
bool push(int element) {
18-
if ((this->elements * TYPE_SIZE) == sizeof(this->arr)) {
19-
return false;
20-
};
21-
this->arr[elements] = element;
22-
elements++;
23-
return true;
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++;
2422
}
2523

2624
bool isEmpty() {
27-
if (!this->elements) {
25+
if (!this->index) {
2826
return true;
2927
}
3028
return false;
3129
}
3230

33-
bool pop() {
31+
int pop() {
3432
if (this->isEmpty()) {
35-
return false;
33+
throw std::logic_error("Stack is empty!");
3634
}
37-
this->arr[this->elements - 1] = 0;
38-
elements--;
39-
return true;
35+
index--;
36+
int value = this->array[this->index];
37+
this->array[this->index] = 0;
38+
return value;
4039
}
4140

42-
int top() {
43-
if (this->isEmpty()) {
44-
return -1;
41+
void print() {
42+
std::cout << "[ ";
43+
for (int i = 0; i < this->index; i++) {
44+
std::cout << this->array[i] << " ";
4545
}
46-
return this->arr[this->elements - 1];
47-
}
48-
49-
int getSize() {
50-
return sizeof(this->arr) / TYPE_SIZE;
46+
std::cout << "]" << std::endl;
5147
}
5248
};
5349

5450
int main() {
5551
// Create a pointier to a new Stack instance
5652
Stack* stack = new Stack();
5753

58-
// Insert Elements, then removes
54+
std::cout << "Push(1, 2, 4)" << std::endl;
5955
stack->push(1);
6056
stack->push(2);
6157
stack->push(4);
62-
std:: cout << stack->top() << std::endl;
58+
stack->print();
59+
60+
std::cout << "Pop()" << std::endl;
6361
stack->pop();
64-
std:: cout << stack->top() << std::endl;
62+
stack->print();
63+
6564
stack->pop();
6665
stack->pop();
6766

68-
std::cout << "--------------------" << "\n";
69-
70-
// Try to insert beyond max size
71-
for (int i = 0; i < 15; i++) {
72-
std::cout << stack->push(i) << std::endl;
73-
}
74-
75-
std::cout << "--------------------" << "\n";
76-
77-
// Show and remove stack top element
78-
for (int i = 0; i < stack->getSize(); i++) {
79-
std::cout << stack->top() << std::endl;
80-
stack->pop();
81-
}
67+
std::cout << "Empty Stack" << std::endl;
68+
stack->print();
8269
}

0 commit comments

Comments
 (0)