Skip to content

Commit 4e02365

Browse files
authored
Dynamic Stack Corrections
Dynamic Stack Corrections
1 parent 2b5f46c commit 4e02365

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

src/chapter04stacks/DynamicArrayStack.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ private void expand() {
6464
int[] newstack=new int[length<<1]; // or 2* length
6565
System.arraycopy(stackRep,0,newstack,0,length);
6666
stackRep=newstack;
67+
this.capacity = this.capacity<<1;
6768
}
6869

6970
// dynamic array operation: shrinks to 1/2 if more than than 3/4 empty
@@ -77,6 +78,7 @@ private void shrink() {
7778
int[] newStack=new int[length];
7879
System.arraycopy(stackRep,0,newStack,0,top+1);
7980
stackRep=newStack;
81+
capacity = length;
8082
}
8183

8284
// Inspects the element at the top of the stack. This method runs in O(1) time.
@@ -93,6 +95,7 @@ public int pop() throws Exception {
9395
throw new Exception("Stack is empty.");
9496
data = stackRep[top];
9597
stackRep[top--] = Integer.MIN_VALUE; // dereference S[top] for garbage collection.
98+
shrink();
9699
return data;
97100
}
98101

@@ -110,4 +113,4 @@ public String toString() {
110113
}
111114
return s + "]";
112115
}
113-
}
116+
}

0 commit comments

Comments
 (0)