简体   繁体   中英

Stack implemented with dynamic array

Suppose we implement a stack using a dynamically allocated array. If the array fills, we are faced with a dilemma. From among the following choices, select the one that best describes our strategy for handling a filled array.

(a) We declare a new array, twice as big as the original, and copy the data into the new space for a total cost of O(n), over a sequence of n pushes.

(b) We declare another array and keep track of which of the two (or more) arrays contain the current top of the stack in a private member of the stack class. This costs us O(1) per push.

(c) For some fixed k, we create a new array of size n + 2^k and copy the data into the new space for an average cost of O(1) per push operation.

(d) We avoid implementing a stack using a dynamically allocated array, because it is inefficient to have to reallocate memory.

(e) None of these answers is a reasonable response.

I'm pretty sure the correct answer is a, but I dont understand why that would be the best one over the others? Are the others even practical? They seem ok to me. For example, c is almost the same thing as `a, no? Why is doubling more advantageous then increasing by a constant amount? What about the other options-why dont they work?

Say your stack was 128 elements and you ended up having to store 4096 elements in it. How many times would you have to resize the array when doubling vs. extending it by a constant 128 items each time?

This looks like homework and possibly a take-home test, so I'll deliberately leave something out of my answers.

a) Attempt to supply proof for the O(n) claim. Compare with your proof for b).

b) How do you store the set of subarrays in use? (It's turtle's all the way down.)

c) Attempt to supply proof for the O(1) assertion. Compare with your proof for a).

d) All alternatives have their own inefficiencies. Compare them. Note that in real-time programming you can't use a dynamically reallocated array, and you must use something like a linked list. Why?

e) If any of the above are reasonable, this is trivially false. And vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM