@@ -40,6 +40,20 @@ class Stack {
40
40
*/
41
41
~Stack () { delete[] stack; }
42
42
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
+
43
57
/* *
44
58
* @brief Pushes an element onto the stack
45
59
*
@@ -48,7 +62,7 @@ class Stack {
48
62
* otherwise
49
63
*/
50
64
bool push (T element) {
51
- if (stackIndex == stackSize ) {
65
+ if (full () ) {
52
66
return false ;
53
67
} else {
54
68
stack[stackIndex++] = element;
@@ -63,7 +77,7 @@ class Stack {
63
77
* @throws std::out_of_range if the stack is empty
64
78
*/
65
79
T pop () {
66
- if (stackIndex == 0 ) {
80
+ if (empty () ) {
67
81
throw std::out_of_range (" Stack is empty" );
68
82
} else {
69
83
return stack[--stackIndex];
@@ -86,10 +100,10 @@ class Stack {
86
100
* @throws std::out_of_range if the stack is empty
87
101
*/
88
102
T topmost () const {
89
- if (stackIndex > 0 ) {
90
- return stack[stackIndex - 1 ];
91
- } else {
103
+ if (empty ()) {
92
104
throw std::out_of_range (" Stack is empty" );
105
+ } else {
106
+ return stack[stackIndex - 1 ];
93
107
}
94
108
}
95
109
@@ -100,10 +114,10 @@ class Stack {
100
114
* @throws std::out_of_range if the stack is empty
101
115
*/
102
116
T bottom () const {
103
- if (stackIndex > 0 ) {
104
- return stack[0 ];
105
- } else {
117
+ if (empty ()) {
106
118
throw std::out_of_range (" Stack is empty" );
119
+ } else {
120
+ return stack[0 ];
107
121
}
108
122
}
109
123
};
@@ -116,7 +130,10 @@ class Stack {
116
130
static void test () {
117
131
data_structures::Stack<int > stack (5 );
118
132
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
+
120
137
assert (stack.push (10 ) == true );
121
138
assert (stack.push (20 ) == true );
122
139
assert (stack.push (30 ) == true );
@@ -134,6 +151,9 @@ static void test() {
134
151
assert (stack.pop () == 20 );
135
152
assert (stack.pop () == 10 );
136
153
154
+ assert (stack.empty () == true );
155
+ assert (stack.full () == false );
156
+
137
157
// Test for exceptions when stack is empty
138
158
try {
139
159
stack.topmost ();
0 commit comments