Professional Documents
Culture Documents
13-CISC - CMPE 365 - Dynamic Stacks
13-CISC - CMPE 365 - Dynamic Stacks
if t > n {
for i = 1 to n {
B[i] = A[i]
n = 2n
free A
A[t] = x
t = t + 1
9 5, 6, 7, 8 1, 2, ..., 8
2
+ 1 … n] , should have
two
credits. That makes a total of n credits in the array.
k k
= (1 + k) + (2) − (2 ) because elements contribute 2 credits each
2 2
= 3
t = t - 1
x = A[t]
if t <= n/4+1 {
for i = 1 to n/4 {
B[i] = A[i]
n = n/2
free A
A = B
return x
watkins.cs.queensu.ca/~jstewart/365/notes/13/13-dynamic-stacks.html 2/4
9/8/22, 2:19 PM CISC/CMPE 365 - Dynamic Stacks
Exercise
Why not shrink the array to one-quarter its current size once it becomes one-quarter full?
solution
We cannot guarantee that there are credits on A[ + 1 … n] because there might never have been elements
in
n
4
+ 1…
n
2
+ 1] .
4
+ 1 credits to pay for the n
4
elements that get
copied when
the array shrinks.
= 1 + 1 − 0 where one credit is bought and placed on the array slot that contained the p
= 2
n n
= (1 + ) + (1) − ( + 1)
4 4
= 1
watkins.cs.queensu.ca/~jstewart/365/notes/13/13-dynamic-stacks.html 3/4
9/8/22, 2:19 PM CISC/CMPE 365 - Dynamic Stacks
Conclusion
We can maintain a dynamic stack in amortized O(1) cost per operation!
watkins.cs.queensu.ca/~jstewart/365/notes/13/13-dynamic-stacks.html 4/4