Skip to content

Commit 19fc4b4

Browse files
committed
ref: add full and empty methods
1 parent e741146 commit 19fc4b4

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

data_structures/stack_using_array.cpp

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,20 @@ class Stack {
4040
*/
4141
~Stack() { delete[] stack; }
4242

43+
/**
44+
* @brief Checks if the stack is full
45+
*
46+
* @return true if the stack is full, false otherwise
47+
*/
48+
bool full() const { return stackIndex == stackSize; }
49+
50+
/**
51+
* @brief Checks if the stack is empty
52+
*
53+
* @return true if the stack is empty, false otherwise
54+
*/
55+
bool empty() const { return stackIndex == 0; }
56+
4357
/**
4458
* @brief Pushes an element onto the stack
4559
*
@@ -48,7 +62,7 @@ class Stack {
4862
* otherwise
4963
*/
5064
bool push(T element) {
51-
if (stackIndex == stackSize) {
65+
if (full()) {
5266
return false;
5367
} else {
5468
stack[stackIndex++] = element;
@@ -63,7 +77,7 @@ class Stack {
6377
* @throws std::out_of_range if the stack is empty
6478
*/
6579
T pop() {
66-
if (stackIndex == 0) {
80+
if (empty()) {
6781
throw std::out_of_range("Stack is empty");
6882
} else {
6983
return stack[--stackIndex];
@@ -86,10 +100,10 @@ class Stack {
86100
* @throws std::out_of_range if the stack is empty
87101
*/
88102
T topmost() const {
89-
if (stackIndex > 0) {
90-
return stack[stackIndex - 1];
91-
} else {
103+
if (empty()) {
92104
throw std::out_of_range("Stack is empty");
105+
} else {
106+
return stack[stackIndex - 1];
93107
}
94108
}
95109

@@ -100,10 +114,10 @@ class Stack {
100114
* @throws std::out_of_range if the stack is empty
101115
*/
102116
T bottom() const {
103-
if (stackIndex > 0) {
104-
return stack[0];
105-
} else {
117+
if (empty()) {
106118
throw std::out_of_range("Stack is empty");
119+
} else {
120+
return stack[0];
107121
}
108122
}
109123
};
@@ -116,7 +130,10 @@ class Stack {
116130
static void test() {
117131
data_structures::Stack<int> stack(5);
118132

119-
// Test push, pop, topmost and bottom operations
133+
// Test push, pop, topmost, bottom, full, and empty operations
134+
assert(stack.empty() == true);
135+
assert(stack.full() == false);
136+
120137
assert(stack.push(10) == true);
121138
assert(stack.push(20) == true);
122139
assert(stack.push(30) == true);
@@ -134,6 +151,9 @@ static void test() {
134151
assert(stack.pop() == 20);
135152
assert(stack.pop() == 10);
136153

154+
assert(stack.empty() == true);
155+
assert(stack.full() == false);
156+
137157
// Test for exceptions when stack is empty
138158
try {
139159
stack.topmost();

0 commit comments

Comments
 (0)