From cc5c1fe62e1684a07de8aa108da41cbf6555537c Mon Sep 17 00:00:00 2001 From: cosmeoes Date: Tue, 20 Jun 2017 23:13:22 -0600 Subject: [PATCH] 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. --- data_structures/Stacks.java | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/data_structures/Stacks.java b/data_structures/Stacks.java index dbb2a6217..4e2b08545 100644 --- a/data_structures/Stacks.java +++ b/data_structures/Stacks.java @@ -38,8 +38,12 @@ class Stack{ * @param value The element added */ public void push(int value){ - top++; - stackArray[top] = value; + if(!isFull()){ //Checks for a full stack + 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 */ 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 */ 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; + } } /**