Skip to content

Commit 68ff303

Browse files
William O'BrienWilliam O'Brien
William O'Brien
authored and
William O'Brien
committed
Added Resize for Stacks
1 parent e44016c commit 68ff303

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

data_structures/Stacks/Stacks.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public void push(int value){
4242
top++;
4343
stackArray[top] = value;
4444
}else{
45-
System.out.println("The stack is full, can't insert value");
45+
resize(maxSize*2);
4646
}
4747
}
4848

@@ -54,7 +54,12 @@ public void push(int value){
5454
public int pop(){
5555
if(!isEmpty()){ //Checks for an empty stack
5656
return stackArray[top--];
57-
}else{
57+
}
58+
59+
if(top < maxSize/4){
60+
resize(maxSize/2);
61+
}
62+
else{
5863
System.out.println("The stack is already empty");
5964
return -1;
6065
}
@@ -74,6 +79,16 @@ public int peek(){
7479
}
7580
}
7681

82+
private void resize(int newSize){
83+
private int[] transferArray = new int[newSize];
84+
85+
for(int i = 0; i < stackArray.length(); i++){
86+
transferArray[i] = stackArray[i];
87+
stackArray = transferArray;
88+
}
89+
maxSize = newSize;
90+
}
91+
7792
/**
7893
* Returns true if the stack is empty
7994
*

0 commit comments

Comments
 (0)