diff --git a/data_structures/Stacks/Stacks.java b/data_structures/Stacks/Stacks.java index 2158563173ba..95469b91c4b3 100644 --- a/data_structures/Stacks/Stacks.java +++ b/data_structures/Stacks/Stacks.java @@ -42,7 +42,7 @@ public void push(int value){ top++; stackArray[top] = value; }else{ - System.out.println("The stack is full, can't insert value"); + resize(maxSize*2); } } @@ -54,7 +54,12 @@ public void push(int value){ public int pop(){ if(!isEmpty()){ //Checks for an empty stack return stackArray[top--]; - }else{ + } + + if(top < maxSize/4){ + resize(maxSize/2); + } + else{ System.out.println("The stack is already empty"); return -1; } @@ -74,6 +79,16 @@ public int peek(){ } } + private void resize(int newSize){ + private int[] transferArray = new int[newSize]; + + for(int i = 0; i < stackArray.length(); i++){ + transferArray[i] = stackArray[i]; + stackArray = transferArray; + } + maxSize = newSize; + } + /** * Returns true if the stack is empty *