Skip to content

Commit cc5c1fe

Browse files
authored
Added a few edge cases in the stack class
Added an if statement to: >The push method to make sure the stack wasn't full. >The pop method to make sure the stack wasn't empty. > The peek method to make sure the stack wasn't empty.
1 parent 4c6ea58 commit cc5c1fe

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

data_structures/Stacks.java

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,12 @@ public Stack(int size){
3838
* @param value The element added
3939
*/
4040
public void push(int value){
41-
top++;
42-
stackArray[top] = value;
41+
if(!isFull()){ //Checks for a full stack
42+
top++;
43+
stackArray[top] = value;
44+
}else{
45+
System.out.prinln("The stack is full, can't insert value");
46+
}
4347
}
4448

4549
/**
@@ -48,7 +52,12 @@ public void push(int value){
4852
* @return value popped off the Stack
4953
*/
5054
public int pop(){
51-
return stackArray[top--];
55+
if(!isEmpty()){ //Checks for an empty stack
56+
return stackArray[top--];
57+
}else{
58+
System.out.println("The stack is already empty");
59+
return -1;
60+
}
5261
}
5362

5463
/**
@@ -57,7 +66,12 @@ public int pop(){
5766
* @return element at the top of the stack
5867
*/
5968
public int peek(){
60-
return stackArray[top];
69+
if(!isEmpty()){ //Checks for an empty stack
70+
return stackArray[top];
71+
}else{
72+
System.out.println("The stack is empty, cant peek");
73+
return -1;
74+
}
6175
}
6276

6377
/**

0 commit comments

Comments
 (0)