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.
This commit is contained in:
parent
4c6ea58203
commit
cc5c1fe62e
@ -38,8 +38,12 @@ class Stack{
|
|||||||
* @param value The element added
|
* @param value The element added
|
||||||
*/
|
*/
|
||||||
public void push(int value){
|
public void push(int value){
|
||||||
top++;
|
if(!isFull()){ //Checks for a full stack
|
||||||
stackArray[top] = value;
|
top++;
|
||||||
|
stackArray[top] = value;
|
||||||
|
}else{
|
||||||
|
System.out.prinln("The stack is full, can't insert value");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -48,7 +52,12 @@ class Stack{
|
|||||||
* @return value popped off the Stack
|
* @return value popped off the Stack
|
||||||
*/
|
*/
|
||||||
public int pop(){
|
public int pop(){
|
||||||
return stackArray[top--];
|
if(!isEmpty()){ //Checks for an empty stack
|
||||||
|
return stackArray[top--];
|
||||||
|
}else{
|
||||||
|
System.out.println("The stack is already empty");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -57,7 +66,12 @@ class Stack{
|
|||||||
* @return element at the top of the stack
|
* @return element at the top of the stack
|
||||||
*/
|
*/
|
||||||
public int peek(){
|
public int peek(){
|
||||||
return stackArray[top];
|
if(!isEmpty()){ //Checks for an empty stack
|
||||||
|
return stackArray[top];
|
||||||
|
}else{
|
||||||
|
System.out.println("The stack is empty, cant peek");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
Loading…
Reference in New Issue
Block a user